← Python for Beginners
0 of 27 lessons done0%

Practice · Lesson 24 of 27

Practice: prime number

A prime number is greater than 1 and divisible only by 1 and itself: 2, 3, 5, 7, 11, 13 ...

To check n, try dividing it by every number from 2 up to n - 1. If any divides it exactly, it is not prime.

A faster trick: you only need to check up to the square root of n. If n had a factor bigger than its square root, it would also have one smaller than it. So loop while i * i <= n.

n = 29
i = 2
while i * i <= n:
    ...
    i += 1

This is one of the most asked questions in coding rounds. Remember: 0 and 1 are not prime, and 2 is prime.

Your task

Write a function is_prime(n) that returns True if n is prime and False otherwise.