Posted by Somesh Shinde
On
Tuesday, 28 June 2016
Prime Number
Logic: Prime Number are divisible by itself only.
Not divisible by any Number | Divisible by 2 ...no need to check further | Divisible by 3 ...no need to check further |
7%2=1 7%3=1 7%4=3 7%5=2 7%6=1 | 8%2=0 8%3= 8%4= 8%5= 8%6= 8%7= | 9%2=1 9%3=0 9%4 9%5 9%6 9%7 9%8 |
Numbers are not divisible by more than half of the number |
No need to check upto 6 check upto 3 only | No need to check upto 7 check upto 4 only | No need to check upto 8 check upto 4 only |
Program | Output |
//Note: Scanner class work with JDK1.5 or above
import java.util.*;
class Prime
{
public static void main(String args[])
{
int n, i, res;
boolean flag=true;
Scanner scan= new Scanner(System.in);
System.out.println("Please Enter a No.");
n=scan.nextInt();
for(i=2;i<=n/2;i++)
{
res=n%i;
if(res==0)
{
flag=false;
break;
}
}
if(flag)
System.out.println(n + " is Prime Number");
else
System.out.println(n + " is not Prime Number");
}
}
| Please Enter a No.: 7
7 is Prime Number
|
|
|
0 comments:
Post a Comment