Sunday, August 16, 2009

Smallest Prime Number Java Program

Hi friends, today Java Code Online will be discussing the Java code for finding the smallest Prime number, which is greater then the number provided by the user.

The Java code starts by asking the user to enter a number, and then it generates the smallest Prime number which is greater then the user provided number.

The Java Code is given below:-

////////////////////////////////////

package developer;

import java.util.Scanner;

public class SmallestPrime {

public static void main(String[] args)
{
int num = 0;
System.out.println("Enter a number:");
//get the input from the console
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 smallest prime number which is greater then or equal to the number provided is: "+num);
}
else
{
if(num > 0)
checkPrime(num+1);//Recursion in use
else
System.out.println("Number out of range");
}
}
}
////////////////////////////////

Hope that the provided Java code was beneficial to you all. Keep checking Java Code Online for more info on Java.

Related Programs
Prime Number program in Java
Largest Prime number Java Program

No comments:

Post a Comment

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