Write Python. Understand every error.

Open the editor

Python programs · Numbers

Python program to check a prime number

A prime number has exactly two divisors: 1 and itself. To test one, try dividing it by smaller numbers.

Approach

  1. Numbers below 2 are not prime.
  2. Try every divisor from 2 up to the square root of the number.
  3. If one divides it exactly, the number is not prime, so stop early with break.

The program

n = int(input())
if n < 2:
    prime = False
else:
    prime = True
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            prime = False
            break
print(n, "is prime" if prime else "is not prime")

Sample run

Input
29
Output
29 is prime

Run this program in Py-CRAFT

How the code works

Only divisors up to the square root need checking, because divisors come in pairs: if n = a × b, one of the two is at most the square root. That keeps the loop short. For a number near ten million you check about 3,162 divisors instead of ten million. break leaves the loop as soon as a divisor is found.

Try changing it

Common mistakes

Learn the ideas

More programs

Share this page: