6 is prime


#1

Why am I getting a message that this fails on is_prime(3) with this?

def is_prime(x):
    if x < 2:
        return False
    
    elif x > 2:
        n = 2
        while n < x:
            if x % n == 0:
                return False
                break
            n += 1
    else:
        return True

print is_prime(6)

#2

Hi,

Let's go through your code with the number 3, to understand, what's happening:

elif 3 > 2: #this is our case
    n = 2
    while n < 3:
        if 3 % n == 0:
            return False
        n += 1

Let's take a closer look at the while-loop:

while 2 < 3:
    if 3%2 == 0: #won't go in, because it's 1
n += 1 #n = 3 now

Now your loop won't work anymore, because 3 (n) < 3 (x) isn't True so you fell out of the loop. Now you haven't got anything to return, because you only return something if x%n == 0, so your function will return None, that's why it won't work. The program doesn't tell you anything if you type the number 3 :disappointed:

Solution:

Delete the "break" (return will kick you out of the function, so you don't need to break the loop :stuck_out_tongue_winking_eye:)
and then, add an else to the while-loop:

def is_prime(x):
    if x < 2:
        return False
    
    elif x > 2:
        n = 2
        while n < x:
            if x % n == 0:
                return False
            n += 1
        else:
            return True
    else:
        return True

#3

Thank you! I thought it must be some basic thing that was staring me in the face.


#4

Hello, can you please clarify why you used n += 1? It's quite confusing for the first time. Thanks!


#5

The elif section is the part that runs through the calculations to determine if a number is a prime or not. To do that, it's necessary to divide the number by all numbers from 2 through the integer before the number itself.

For example: to determine if 13 is a prime number, you need to divide it by 2, then by 3, then by 4, etc., until finally you divide it by 12.

The n is a container to hold the integer that the number is being divided by in any given iteration. So n needs to increase by one after each calculation.


#6

Ah ok! Now I get it. Thanks for the explanation!