Suppose, the value entered is say 121. It is assigned to an integer variable num. Now, num is divided by all the numbers from 2 to 8 (because a number can be divided by 1 and itself) (% rehrrns remainder). If the number is divided by any number from 2 to 8, its remainder will come to be 0 and in that case the message “Number is not prime” is displayed on the screen. 121 is not divisible by 2 but is no doubt divisible by 3 which returns remainder as 0 and hence it is not a prime number.
Algorithm For Prime Number Program:
step 1: Read num
step 2: Set b=l, c=0
step 3: Repeat through step-5 while (b <= num)
step 4: If (num mod b) equals to 0 then set c = c + 1
step 5: b = b + l
step 6: If c equals to 2 then print “num is prime”
Else print “num is not prime”
step 7: Exit
Here is the Java Example for Prime Number Program:
import java.util.Scanner;
public class PrimeNumber
{
public static void main(String args[])
{
int num,b,c;
Scanner s=new Scanner(System.in);
System.out.println("Enter A Number");
num =s.nextInt();
b=1;
c=0;
while(b<= num)
{
if((num%b)==0)
c=c+1;
b++;
}
if(c==2)
System.out.println(num +" is a prime number");
else
System.out.println(num +" is not a prime number");
}
}