Java program to check whether the given number is prime or not
A number is said to be prime if it is divisible by 1 and itself. otherwise it is composite.
Algorithm
Step 1: START.
Step 2: read the number n.
Step 3: Check the divisibility of the number from 2 to n/2.
Step 4: If number is divisible by any of the numbers above . It isn’t prime.
Step 5 :Else it is prime.
Step 6: STOP.
Source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.util.*; class Prime { public static void main(String args[]) { System.out.println("\n \n *** www.programmingposts.com *** \n \n"); System.out.println("<< JAVA Program to find the given number is prime or not >> \n \n"); Scanner scanner = new Scanner(System.in); System.out.println("Enter the number:"); int num = scanner.nextInt(); int m = num/2; for(int i=2;i<=m;i++) { if(num%i == 0) { System.out.println(num + " is a Composite number"); break; } else { System.out.println(num + " is a Prime number"); break; } } } } |
Explanation:
If we want to check whether the given number (num) is a prime or not then divide the number by 2 and then you will get a value then divide the number (num) with all the numbers less than num/2 if you are not getting zero then it is a prime number
ex: x=23
(num/2)=approx (11)
now divide the number 23 with 2…..upto 11 . If you get zero anywhere then it is not a prime number
But here we won’t get a zero since 23 is a prime number
Output:
C:\Users\santo\Desktop\new>javac Prime.java
C:\Users\santo\Desktop\new>java Prime
*** www.programmingposts.com ***
<< JAVA Program to find the given number is prime or not >>
Enter the number:
11
11 is a Prime number
Screenshot of Output: