Is_prime


#1

my code doesn't seem to be working. can someone please please tell me why?
my code:
def is_prime(x):
if x < 2:
return False
answer = False
if x == 2:
return True
for count in range(2, x):
if x == 2:
return True

    elif x < 2:
        return False

    elif x > 2 and x-1 / count == 0:
        answer = False

    elif x > 2 and x-1 / count != 0:
        answer = True
return answer

my error message:
Oops, try again. Your function fails on is_prime(4). It returns True when it should return False.


#2

Quite a lot of repetition in the above, and that may be clouding the issue. Break the problem down into three parts.

  1. less than 2
  2. greater than 2
  3. equal to 2

Since the instructions are essentially for a brute force function with no special conditions (not iterating odd only, using full range) we can treat this like so:

x < 2  =>  return False

This covers everything less than 2, including negative values for x.

x > 2  => run the test loop

otherwise, x must equal 2, so the final return (outside of the if) is True.

The test loop is fairly straight forward. Iterate over every number in the range 2 to x, and if any are divisible into x, return False. There will be no else or elif anywhere in your code.


#3

my new code after taking your suggestion:

def is_prime(x):
    answer = False
    n = 2
     if x > 2:
        for count in range(2, x):
            if x % n == 1:
                n += 1
                answer = True
            else:
                n += 1
    elif x == 2:
        answer = True
    return answer

is this what you mean?
if it is, then it still fails on is_prime(4).
so how would i fix this error message and change it into what you said it should be?


#4

Closer. Since we are working out a brute force algorithm, we do not need any conditionals except < 2 and > 2. That means no elif and no else anywhere in the code.

if x < 2: return False
if x > 2:
    for n in range(2,x):
        # return False if x % n == 0
return True

#5

thank you. i have been working on this exercise for 6 days.


#6

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