Showing posts with label check prime program. Show all posts
Showing posts with label check prime program. Show all posts

Thursday, February 9, 2012

Java Prime Number Program - Check Number is Prime or Not

It is sample java example of prime number. In this java program user input any number. Program checks accepted number is prime number or not a prime number.

Program Code
//Java Prime Number Program
import java.util.*;
class PRIME
{
 int prime(int n)
 {
  int i;
  for(i=2;i<=n/2;i++)
  {
   if((n%i)==0)
   {
    break;
   }
  }
  if(i>n/2 && n!=1)
  return 1;
  return 0;
 }
}
public class PRIME_MAIN
{
 public static void main(String args[])
 {
  PRIME p1=new PRIME();
  Scanner object1=new Scanner(System.in);
  System.out.println("");
  System.out.println("******PRIME NUMBER PROGRAM******");
  System.out.print("Enter any number: ");
  int num=object1.nextInt();
  int flag=p1.prime(num);
  if(flag==1)
  System.out.println(num+" is a prime number");
  else
  System.out.println(num+" is not a prime number");
 }
}


Output
Copy code and paste into notepad and save as "PRIME_MAIN.java".