Algorithms and Data Structures · Junior · Question 64 of 75

What is the time complexity of the isPrime check below?

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

Explanation

The loop stops when i * i > n, so it runs at most √n times. A divisor larger than √n would pair with one smaller than √n, which the loop has already checked.

Further reading

Problem with a question

Algorithms and Data Structures · Junior · question 64

Test yourself

Take the Algorithms and Data Structures · Junior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz