Ir al contenido
Ayotl

← Todos los retos

Interview challenge · easy · math, loops

Prime Number Check

El reto

El enunciado va en inglés, igual que en el vídeo.

Write a function that returns true if an integer n is prime: greater than 1 and divisible only by 1 and by itself.

Example

17  ->  true
21  ->  false   (3 x 7)
1   ->  false   (primes start at 2)
97  ->  true
2   ->  true    (the only even prime)

Idea: trial division. If n has a divisor d bigger than its square root, then n / d is a divisor smaller than the square root, so it is enough to try d while d * d <= n. That is O(sqrt(n)) time instead of O(n). Comparing d * d with n also avoids computing a floating-point square root. The usual follow-up, all primes up to N, is the Sieve of Eratosthenes.

La solución

# Prime Number Check - ayotl.dev
def is_prime(n):
    if n < 2:
        return False
    d = 2
    # divisors pair up around sqrt(n)
    while d * d <= n:
        if n % d == 0:
            return False
        d += 1
    return True


for n in [17, 21, 1, 97, 2]:
    ok = is_prime(n)
    print(n, "true" if ok else "false")

$ python3 prime_number_check.py

17 true

21 false

1 false

97 true

2 true

El vídeo

Ver en YouTube →