Why does is_prime fail for some numbers?


#1

Question

Why does is_prime fail for some numbers?

Answer

If your code is failing for some numbers, it’s likely because you’re returning too soon, or because you’re returning the wrong thing in the wrong place. Without giving away the answer, take a look at the example control flow pseudo code below:

# From hint: any number less than 2 is not prime
if x is less than 2:
  return x is not prime

# This loop is where we put our number to the test and return False
# so the function exits immediately if x isn’t prime
for n from 2 to x:
  if x is evenly divisible by n:
    return x is not prime

# If we made it here, our number must be prime because none
# of the other return statements were executed!
return x is prime

FAQ: Learn Python - Practice Makes Perfect - factorial FAQ: Learn Python - Practice Makes Perfect - is_prime
#2

How is this code not returning 2 as False.


#3

The loop does not run when x is 2, so it falls to the bottom return line.


#4

Sorry, I am not getting the for condition when x is 2. It should return false as 2%2 = 0.


#5

The parameters set in the range do not permit x to enter the loop if it is 2.

x = 2

range(2, x)  =>  (2..1)  =>  []

#6

thank you, mtf…
didn’t consider that


#7

A post was split to a new topic: Don’t understand about why the solution works


#8

9 posts were split to a new topic: Range in is_prime