Wednesday, July 1, 2015

Prime Number Program in Java

  1. prime number is a whole number greater than 1, whose only two whole-number factors are 1 and itself. The first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29.



import java.util.*;

public class Prime {

public static void main(String[] args) {

Scanner scn =new Scanner(System.in);
System.out.println(" type a no. to  check the prime no.");
int n=scn.nextInt();
for(int j=1;j<=n;j++)
{
int a=1;
      for(int i=2;i<=j-1;i++)
     {
            if(j%i==0)
           {
                 a=0;
                 break;
           }
    }

if(a==1)
{
System.out.println(j);
}

}
}

}


Or to check a single no. is it prime or not.

public class NewPrime {

public static void main(String[] args) {

Scanner scn=new Scanner(System.in);
System.out.println("Provide input to check the prime no or not");
int n=scn.nextInt();
prime(n);

}
public static void prime(int n)
{

boolean a=true;
for(int j=2 ;j<n;j++)
{
if(n%j==0)
{
a=false;
break;
}
}
if(a==true)
{
System.out.println("prime");
}
else
{
System.out.println("not prime");

}
  }


}


0 comments:

Post a Comment