Monday, July 20, 2009

Java code for Prime Number, Prime Number Example in Java

Hi friends, welcome back to Java Code Online. Today I am going to give you the Java Code for finding out whether a number is prime or not. A prime number is a number which is divisible by 1 or by itself only. The prime number is divisible by no other number except one and itself. Prime number is of utmost importance in Mathematics, and is used extensively in this field.

The Java code for finding a number is prime or not, is displayed below:-

import java.io.*;

public class primeNumber {
public static void main(String[] args)
{
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
System.out.println("Enter the number you want to test for prime number:");
int num =0;
int check = 0;
try {
num = Integer.parseInt(br.readLine());
for (int i=2; i < num/2; i++ ){
if(num%i == 0)
{
check = 0;
break;
}
else
{
check = 1;
}
}
if(check == 1 || num == 2)
{
System.out.println("The number is prime");
}
else
{
System.out.println("The number is not prime");
}
} catch (NumberFormatException e) {
System.out.println("Kindly enter a proper integer number");

} catch (IOException e) {
System.out.println("There is some error in the input output handling");
}
}
}

I hope that this Java Code for finding a number is prime or not is helpful to you all. For more info on Java,keep buzzing Java Code Online.

1 comment:

  1. Thanks for the code. It really helped. In would like to know, is there any other way also to implement the prime number program. I was thinking of using recursion. I hope if you could guide me on this. Moreover i need the code for file read and write in java. Thanks for the help anyways. keep posting..

    ReplyDelete

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