Prime number check

Return True if n is a prime number (it has exactly two divisors: 1 and itself), otherwise False.

Write is_prime(n) in Python, isPrime(n) in JavaScript or TypeScript, or int is_prime(int n) in C. Level: Easy.

Examples

Input: n = 7
Output: True
Input: n = 10
Output: False
  • 0 ≤ n ≤ 1,000,000
  • 0 and 1 are not prime

Hint

Handle n < 2 first. Then you only need to try divisors up to the square root of n: stop when i × i > n.

The approach, step by step

  1. n < 2?
  2. i = 2
  3. i × i ≤ n?
  4. n % i == 0?
  5. i = i + 1
  6. Return True
  7. Return False

← All practice problems

Try AI Flowchart free →