A number that can divide by own or one only.
For Example: 13, can be dived by only 1 and 13 only. Other prime numbers are 2, 3, 5, 7 , 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, …
947, 953, 967, 971, 977, 983, 991, 997… etc
Exception : 1 is not prime.
Problem
Write a java code to test whether number is prime or not.
Code
import java.util.Scanner;
public class Prime {
public static boolean prim(int num) {
if(num == 2 || num == 3) {
return true ;
}
if(num % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(num);
for(int i=3; i<=sqrt; i += 2) {
if(num % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
System.out.println("Enter no ");
Scanner scanner = new Scanner(System.in);
int cnt = scanner.nextInt();
scanner.close();
if(Prime.prim(cnt) == true) {
System.out.println("Prime number ");
}
else {
System.out.println("Not Prime number ");
}
}
}
Run Code