Primality test by trial division

Easy TimeO(√n) SpaceO(1)

A prime is a whole number above 1 whose only divisors are 1 and itself, so 97 is prime and 91 is not — 91 = 7 × 13. Given an integer n, return true when n is prime and false when it is not. 1 and everything below it are not prime, and 2 is the only even number that is.

Examples

Example 1

Input
n = 97
Output
true
Nothing between 2 and 96 divides 97 exactly.

Example 2

Input
n = 91
Output
false
7 × 13 = 91, so 7 divides it and the answer is false.

The Code

function isPrime(n) {
  if (n < 2) return false;
  if (n % 2 === 0) return n === 2;
  for (let d = 3; d * d <= n; d += 2) {
    if (n % d === 0) return false;
  }
  return true;
}
isPrime(97);
Done
Step through isPrime(97) call by call