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
- n < 2?
- i = 2
- i × i ≤ n?
- n % i == 0?
- i = i + 1
- Return True
- Return False