Check a prime number

MediumIf-Else Programs · 6 of 64

Write a Python program to check whether a given number is prime.

Advertisement
Input
2, 15, 17, 1
Output
2 is prime
15 is not prime
17 is prime
1 is not prime

Approach

  1. Numbers below 2 are not prime.
  2. Try divisors from 2 to the square root; if one divides exactly, it is not prime.

Solution

Python
def is_prime(n):    if n < 2:        return False    for d in range(2, int(n ** 0.5) + 1):        if n % d == 0:            return False    return True for n in [2, 15, 17, 1]:    if is_prime(n):        print(n, "is prime")    else:        print(n, "is not prime")
Output
2 is prime
15 is not prime
17 is prime
1 is not prime

Line by line

Lines 2-3

0 and 1 are not prime by definition.

Line 4

Checking divisors up to √n is enough.

Lines 5-6

Return early as soon as a divisor is found.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More if-else programs

← All 64 If-Else Programs