Java Prime Numbers: A Beginner's Guide to Identifying and Verifying Primes

Java Prime Numbers: A Beginner's Guide to Identifying and Verifying Primes

What is a Prime number?

    A prime number is a number which has only two factors which are 1 and the number itself.  For example, 5 have only two factors which are 1 and 5 only. If we take 8 then it has factors as 1,2,4,8 which is more than 5.
    Now we understood what is a prime number. Now we have to look at how we can implement this logic in our code. From the definition, we know that the prime number has only two factors 1 and the number itself. So if we want to find out the number of factors then we have to divide the number from 1 by the number itself and have to count how much time it got divided. If the number got divided only by two numbers that means it has only two factors concluding it is a prime number and if more than two that means it has more than two factors concluding it is not a prime number. Just take a look at the following algorithm.

Algorithm for finding Prime number


Algorithm for finding Prime number

Code

 import java.util.Scanner;
 
public class PrimeNumber {
 
    public static void main(String[] args) {
        int userNumber;
        int noOfFactor = 0;
 
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a whole number : ");
 
        userNumber = scanner.nextInt();
        scanner.close();
 
        if (userNumber == 1) {
            System.out.println("1 is not a prime number.");
        } else if (userNumber < 1) {
            System.out.println("Please enter a whole number.");
        } else {
            for (int i = 1; i <= userNumber; i++) {
                if (userNumber % i == 0) {
                    noOfFactor++;
                }
            }
 
            if (noOfFactor == 2) {
                // number have only two factors
                System.out.println("It is a prime number.");
            } else {
                // number have more than two factors
                System.out.println("It is not a prime number.");
 
            }
        }
    }
}

Output:

Enter a whole number : 3

It is a prime number.

    Hope you understood how to verify whether the number is a prime number or not. If you still have any doubts then please let me know in the comment.

Comments