Prime number
A prime number is an integer which is greater than 1 whose only factors are 1 and itself. A factor is an integer that can be divided evenly into another number.
Logic
The logic to check a number is prime or not is really simple. We only need to check if the given number is completely divisible by any other smaller number or not, but not by 1 and itself.
After taking input from the user, we have to run one loop up to half of the given number. Now the reason for running one loop up to half of the given number is because we know, a number can only be divisible by a number which is lesser than its half.
Inside the loop we have to check if the given number “num” is completely divisible by current number “i” or not, If yes then set the value of the variable i to num and terminate the loop here, if no then continue the loop.
Once the loop is completed or terminated control comes out of the loop, here we have to check if the value of the variable i is equivalent to the given number or not. If yes then it is not a Prime number otherwise it is a prime number.
Program
import java.util.Scanner; public class CheckPrime { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int i, num; // Take input from user System.out.print("Enter any number : "); num = scanner.nextInt(); for(i = 2; i <= (num / 2); i++) { if((num % i) == 0) { i = num; break; } } if(i == num) { System.out.println("\n" + num + " is not a prime number."); } else { System.out.println("\n" + num + " is a prime number."); } } }
Output
Enter any number : 7
7 is a prime number.