Hackbright Code Challenges

Is Number Prime?: Solution

Is Number Prime?: Solution

Problem

Is Number Prime?

Whiteboard

Easier

Concepts

General, Math

Download

is-prime-solution.zip


def is_prime(num):
    """Is a number a prime number?"""

    # START SOLUTION

    if num < 2:
        return False

    # This is a very naive check -- firstly, we could check once
    # for even numbers and then count up by twos. Secondly, we
    # only have to check up to sqrt(num) -- since if a number is
    # divisible by a number > its square root, the other divisor
    # would be definition be less than its square root.
    #
    # For our purposes, though, this is a reasonable answer for
    # an easy whiteboarding question.

    for n in range(2, num):
        if num % n == 0:
            return False

    return True