![]() |
VOOZH | about |
Given a number n, check whether it is a prime number or not.
Note: A prime number is a number greater than 1 that has no positive divisors other than 1 and itself.
Input:
n = 7
Output:true
Explanation: 7 is a prime number because it is greater than 1 and has no divisors other than 1 and itself.Input:
n = 25
Output:false
Explanation: 25 is not a prime number because it is divisible by 5 (25 = 5 × 5), so it has divisors other than 1 and itself.Input: n = 1
Output: false
Explanation: 1 has only one divisor (1 itself), which is not sufficient for it to be considered prime.
Table of Content
To check if a number n is prime, first see if it's less than 2 — if so, it's not prime. Otherwise, try dividing n by every number from 2 to n - 1. If any number divides it evenly, then n is not prime. If none do, then n is a prime number.
true
The idea is that we only need to check divisors up to √n (i.e., while i * i <= n) because divisors always come in pairs - one smaller and one larger. If a larger divisor exists beyond √n, its smaller paired divisor would have already been checked, making further checks unnecessary.
Every number n can be written as a product of two numbers: n=a×b. Here, a and b are divisors of n.
Example: n = 36
Why does this work?
Consider a number n with a pair of factors (a, b) such that a × b = n.
true
Numbers that are divisible by 2 or 3 are not prime, so we can skip them entirely. To check whether a number is prime, it is sufficient to test only the numbers of the form 6k ± 1 up to √n.
Why all prime greater than 3 can be expressed in the form 6k ± 1?
true