is_prime - need help.. code isn't working


#1
def is_prime (x):
    if ((x <= 0) or (x == 1)):
        return False
    if (x == 2):
        return True
    for n in range(2, x):
        div = 0
        flag = False
        div = x % n
        if div == 0:
            flag = False
            return flag
        else:
            return flag 
    i tried to find what's wrong with the code but i couldn't locate it :(

#2

After playing around with your code to arrive at a solution, this results...

from math import sqrt

def is_prime (x):
    if x < 2:
        return False
    if x % 2 == 0:
        return False or x == 2     # reduce sample space by a factor of 2
    r = int(sqrt(x)) + 1           # reduce sample space by a factor of r
    flag = True
    for n in range(3, r, 2):       # odd numbers between 3 and r inclusive
        if x % n == 0:
            flag = False           # factorable; outta here
            break
    return flag                    # not factorable if still True

It's not lesson tested, but it works in the lab.


#3

There are four assertions in the above algorithm.

  1. A prime cannot be less than 2.
  2. A prime cannot be even unless it is 2.
  3. A number with factors less than or equal to its square root is not prime,
  4. A number is prime, provided it cannot be refuted by...

And we go on with the for statement in an attempt to refute. That's basically what all this boils down to.


#4

The labs repl.it is a good testing ground is you are looking for compatibility issues. It’s a great resource for testing.

Code
from math import sqrt

def is_prime (x):
    if x < 2:
        return False
    if x % 2 == 0:
        return False or x == 2
    r = int(sqrt(x))+1
    flag = True
    for n in range(3, r, 2):
        if x % n == 0:
            flag = False
            break
    return flag 


#5

In conclusion, I have no doubt that this exact example exists somewhere in the CC archives, or even a current 'discuss' topic, but of that I have no actual awares. I only know that intuitively it came up here. If it is meant to be, then so be it. Relish in the discovery, all the same!


#7

Alternatively, a simple change to your code will do the job in a way closer to what the lesson is looking for. Within your for loop, you don't allow for any possibility of flag being marked as True. So any number other than 2 will always return False. Try changing line 8 to flag = True.