Sunday, August 16, 2009

Largest Prime Number Java Program

Hi friends, welcome back to Java Code Online. Today I will be discussing the Java Code, to find the largest prime number, which is smaller then the number provided by the user.

A prime number is a positive integer which is divisible by 1 and itself only. The Java Code for finding the largest Prime number which is lower then the number provided by the user is given below:-

///////////////////////////////////
package developer;

import java.util.Scanner;

public class LargestPrime {

public static void main(String[] args)
{
int num = 0;
System.out.println("Enter a number:");
Scanner scan = new Scanner(System.in);
if(scan.hasNextInt())
{
num = scan.nextInt();
}
checkPrime(num);
}

static void checkPrime(int num)
{
int check = 0;

for (int i=2; i < num; i++ ){
if(num%i == 0)
{
check = 0;
break;
}
else
{
check = 1;
}
}
if(check == 1 || num == 2)
{
System.out.println("The largest prime number which is less then or equal to the number provided is: "+num);
}
else
{
if(num > 2)
checkPrime(num-1);
else
System.out.println("Number out of range");
}
}
}
//////////////////////////////

I hope the above Java code was helpful to you all. For more info on Java keep buzzing Java Code Online.

Related Java Programs
Prime Number program in Java

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.