Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

Java Program to Determine If a Number Is Prime

What Is a Prime Number?

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Classic examples include 2, 3, 5, 7, 11, 13, 17, ….

Key points:

Java Program to Determine If a Number Is Prime

Algorithm overview:

public class PrimeChecker {
    public static void main(String[] args) {
        int numberToCheck = 17; // change this value to test other numbers
        boolean isPrime = true;

        // Edge cases: 0 and 1 are not prime
        if (numberToCheck < 2) {
            isPrime = false;
        } else {
            for (int i = 2; i <= numberToCheck / 2; i++) {
                int remainder = numberToCheck % i;
                System.out.println(numberToCheck + " ÷ " + i + " = " + (numberToCheck / i) + " remainder " + remainder);
                if (remainder == 0) {
                    isPrime = false;
                    break;
                }
            }
        }

        if (isPrime) {
            System.out.println(numberToCheck + " is a prime number.");
        } else {
            System.out.println(numberToCheck + " is not a prime number.");
        }
    }
}

Sample Output

17 ÷ 2 = 8 remainder 1
17 ÷ 3 = 5 remainder 2
17 ÷ 4 = 4 remainder 1
17 ÷ 5 = 3 remainder 2
17 ÷ 6 = 2 remainder 5
17 ÷ 7 = 2 remainder 3
17 ÷ 8 = 2 remainder 1
17 is a prime number.

Try the program above to check any integer, or extend it to find all prime numbers between 1 and 100.

Java

  1. Java Hello World: Your First Program
  2. Java String.contains() Method: How to Check for Substrings – Practical Examples
  3. Constructor Overloading in Java – Explained with Practical Code Examples
  4. Java Multithreading Explained: Concepts, Lifecycle, and Practical Code Examples
  5. Java Program to List Prime Numbers from 1 to 100 – Step‑by‑Step Guide
  6. Generate Fibonacci Sequence in Java: For, While, and Recursive Examples
  7. Java Program to Identify Armstrong Numbers Using For Loop
  8. Java Palindrome Number Checker: Algorithms Using While and For Loops
  9. Insertion Sort Algorithm in Java: A Clear Example & Step‑by‑Step Guide
  10. Selection Sort in Java: Step‑by‑Step Example & Full Code