Write a program to check whether a number is prime, then make it faster.

Check whether a number is prime in Java: the simple version, the square-root version, skipping even numbers, the 6k ± 1 trick, and the Sieve of Eratosthenes for many numbers.

0 0
Read Time:2 Minute, 46 Second

A prime number is a whole number greater than 1 whose only divisors are 1 and itself. This question is common in the TCS NQT coding section and the technical interview because it tests whether you can write correct code first and then improve it step by step.

Step 1: the simple version (O(n))

Try every number from 2 to n − 1. If any of them divides n, it is not prime.

static boolean isPrimeSlow(int n) {
    if (n < 2) return false;
    for (int i = 2; i < n; i++) {
        if (n % i == 0) return false;
    }
    return true;
}

It is correct but slow: for a prime near one billion it does a billion divisions.

Step 2: stop at the square root (O(√n))

If n = a × b and both a and b were bigger than √n, their product would be bigger than n. So at least one divisor is ≤ √n, and you only need to check up to there. Write the condition as i <= n / i instead of i * i <= n so that i * i can never overflow an int.

static boolean isPrime(int n) {
    if (n < 2) return false;
    for (int i = 2; i <= n / i; i++) {
        if (n % i == 0) return false;
    }
    return true;
}

Step 3: skip even numbers and multiples of 3

After handling 2 and 3, every prime is of the form 6k − 1 or 6k + 1. So you can test only 5, 7, 11, 13, 17, 19 and so on, which is about a third of the checks of step 2.

static boolean isPrimeFast(int n) {
    if (n < 2) return false;
    if (n < 4) return true;               // 2 and 3
    if (n % 2 == 0 || n % 3 == 0) return false;
    for (int i = 5; i <= n / i; i += 6) {
        if (n % i == 0 || n % (i + 2) == 0) return false;
    }
    return true;
}

Time is still O(√n), but with a much smaller constant. Space is O(1).

Test cases to say out loud

  • 0, 1 and negative numbers: not prime.
  • 2 and 3: prime (the loop never runs).
  • 4, 9, 25, 49: squares of primes, which catch an off-by-one in the loop condition.
  • 2147483647 (the largest int, and a prime): checks there is no overflow.

Follow-up: all primes up to N (Sieve of Eratosthenes)

If the interviewer asks for every prime up to N, calling isPrime N times costs O(N√N). The sieve does it in O(N log log N): start with every number marked prime, and for each prime p cross out p², p² + p, p² + 2p and so on.

static List<Integer> primesUpTo(int n) {
    boolean[] composite = new boolean[n + 1];
    List<Integer> primes = new ArrayList<>();
    for (int p = 2; p <= n; p++) {
        if (composite[p]) continue;
        primes.add(p);
        for (long m = (long) p * p; m <= n; m += p) composite[(int) m] = true;
    }
    return primes;
}

Common mistakes

  • Returning true for 1.
  • Writing i < Math.sqrt(n) instead of <=, which calls 25 or 49 prime.
  • Calling Math.sqrt on every loop iteration.
  • Forgetting to say the time and space complexity at the end.

This answer was written by Debugger’s Space as practice material. See how TCS hires, step by step, and more TCS practice questions.

Previous post Why do you want to join TCS?
Next post You are asked to work on a technology you have never used. How will you start?
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Close
0
Would love your thoughts, please comment.x
()
x