</>

Technology

Java Programs

Difficulty

Intermediate

Interview Question

Write a Java program to check if a number is prime.

Answer

Check Prime Number in Java

Java
public class PrimeNumber {
    public static void main(String[] args) {
        int num = 29;
        boolean isPrime = true;

        if (num <= 1) {
            isPrime = false;
        } else {
            // Check divisibility from 2 to √num
            for (int i = 2; i <= Math.sqrt(num); i++) {
                if (num % i == 0) {
                    isPrime = false;
                    break;
                }
            }
        }

        if (isPrime)
            System.out.println(num + " is a Prime number");
        else
            System.out.println(num + " is NOT a Prime number");
    }
}

Output

CODE
29 is a Prime number

Why Check Only Up to √n?

CODE
If n = 36:
  Factors: 1×36, 2×18, 3×12, 4×9, 6×6
  After √36=6, factors repeat in reverse
  So checking 2 to 6 is enough

Print All Primes Up to N (Sieve of Eratosthenes)

Java
public class PrintPrimes {
    public static void main(String[] args) {
        int n = 50;

        System.out.print("Primes up to " + n + ": ");
        for (int num = 2; num <= n; num++) {
            boolean prime = true;
            for (int i = 2; i <= Math.sqrt(num); i++) {
                if (num % i == 0) { prime = false; break; }
            }
            if (prime) System.out.print(num + " ");
        }
    }
}

Output

CODE
Primes up to 50: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

Method as Function (Reusable)

Java
public static boolean isPrime(int n) {
    if (n <= 1) return false;
    if (n <= 3) return true;
    if (n % 2 == 0 || n % 3 == 0) return false;
    for (int i = 5; i * i <= n; i += 6) {
        if (n % i == 0 || n % (i + 2) == 0) return false;
    }
    return true;
}

// Usage
System.out.println(isPrime(17));  // true
System.out.println(isPrime(25));  // false

Follow AutomateQA