20. Check Whether a Number Is Prime

Difficulty:EasyPattern:Basic Mathematics / Trial DivisionTime:O(√n)Space:O(1)

Determine whether a given integer is a prime number.

How It Works & Algorithmic Design

A prime number greater than 1 has exactly two positive divisors: 1 and itself.

  1. Numbers less than 2 are not prime.
  2. Try dividing the number by integers starting from 2.
  3. Only test divisors up to the square root of the number.
  4. If any divisor divides evenly, the number is not prime.
  5. Otherwise, it is prime.

Why This Approach Works Best

If a number has a factor larger than its square root, the corresponding paired factor must be smaller than the square root. Therefore checking up to sqrt(n) is sufficient. The time complexity is $O(\sqrt n)$ and space is $O(1)$.

Example Walkthrough

Input

29

29 is greater than 1 and needs to be tested for divisors.

Checks

29 % 2 != 0 | 29 % 3 != 0 | 29 % 4 != 0 | 29 % 5 != 0

Testing only up to sqrt(29), approximately 5.38, is sufficient.

Output

true

No divisor was found, so 29 is prime.

Answer: Check for prime number

function isPrime(n) {
  if (n < 2) return false;

  for (let i = 2; i * i <= n; i++) {
    if (n % i === 0) return false;
  }

  return true;
}

Test possible divisors only up to the square root of the number.

Key Takeaways
  • Numbers below 2 are not prime.

  • Checking divisors only up to the square root is sufficient.

  • The optimized trial-division approach runs in O(√n) time and O(1) space.