A prime number is a whole number greater than 1 that divides only by 1 and by itself. 2, 3, 5, 7 and 11 are prime. 9 is not, because 9 = 3 × 3.
The program
python
import math def is_prime(n): if n < 2: return False for i in range(2, math.isqrt(n) + 1): if n % i == 0: return False return True n = int(input("Enter a whole number: ")) if is_prime(n): print(f"{n} is a prime number") else: print(f"{n} is not a prime number")
Typed in this example: 97. Press Run to type your own.
output
Enter a whole number: 97 97 is a prime number
How it works
- Numbers below 2 (1, 0 and all negative numbers) are not prime, so the function returns
Falsefor them first. - The loop tries each possible divisor
i. Ifn % i == 0, thenidividesnwith no remainder, sonis not prime, andreturn Falseends the function at once. - You only need to test divisors up to the square root of n. If n = a × b, then one of a or b is at most √n. For 97 this means testing 2 to 9, not 2 to 96.
math.isqrt(n)gives the whole-number square root (for 97 it is 9). It is exact even for very large numbers, whichn ** 0.5is not.
Testing several numbers
python
import math def is_prime(n): if n < 2: return False for i in range(2, math.isqrt(n) + 1): if n % i == 0: return False return True for n in [-7, 0, 1, 2, 9, 25, 29]: print(n, is_prime(n))
output
-7 False 0 False 1 False 2 True 9 False 25 False 29 True
25 is a good test: its only divisor apart from 1 and 25 is 5, which is exactly its square root. That is why the loop needs the + 1 in math.isqrt(n) + 1.
Related programs: Print prime numbers in a range.