EXPLANATION for is_prime NEEDED


#1
        Instructions
      
      
        Define a function called is_prime that takes a number x as input.For each number n from 2 to x - 1, test if x is evenly divisible by n.If it is, return False.If none of them are, then return True.

This is my code below:
def is_prime(x):
if x < 2:
return False
elif x ==2 or x==3:
return True
else:
n=2
while n<x:
mod = x%n
if mod==0:
return False
break
else:
n+=1
if n==(x-1):
return True

IT WORKED BUT CAN SOMEONE PLEASE EXPLAIN MY CODE TO..It's copied but I really need to understand it.


#2

Did you pick the most complicated one to copy, or just the first one you came across? There are much simpler versions that are effective. Understanding copied code usually takes some deconstruction and a basic understanding of the concept at hand.

Take for instance:

        n=2
        while n<x:
            mod = x%n
            if mod==0:
                return False
                break
            else:
                n+=1
                if n==(x-1):
                    return True

We would start by simplifying the obvious and removing superfluous code. break is unreachable after return.

if x % n == 0:
    return False

So that gives us,

        n=2
        while n < x:
            if x % n == 0:
                return False
            else:
                n+=1
                if n==(x-1):
                    return True

Now to explain to ourself, what is happening after the else:?

# n is incremented
n += 1
# n is checked against x to see if it has reached a viable limit
if n == x-1:
    return True

But this is rather redundant since when the loop ends we know we have reached the same state, so the conditional is superfluous. Knowing that, we can further rewrite:

        n = 2
        while n < x:
            if x % n == 0:
                return False
            n += 1
        return True

Now it is obvious what the code is doing. Any number greater than 1 that is divisible by a number is not a Prime. So exit the function and return False. The default return value of the function is True.

However we need to go back to the beginning to complete the setup.

def is_prime(x):
    if x < 2:
        return False
    elif x ==2 or x==3:
        return True
    else:
        n = 2

The first condition tests for values that are not greater than 1. A natural number less than 2 is not.

Now the 3 is not exactly a special case, though 2 is. Three is odd and since n is always less than x it will not divide by 2 so will end the loop and return a True. In other words, no need to test for it. No need to test for the exact 2, either, just exclude it from the the loop.

if x > 2:
    n = 2
    # and so on
return True

Since x == 2 never enters the loop, it drops down to the default return value.

So, what have you got left after all this? You tell me.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.