In other languages its correct but here its not working... help!


#1
def is_prime(x):
      count =0
      if x < 2:
          return False
     for i in range(2,9):
          x % i ==0
          count = count +1
         if count == 2:
              print " non prime "
              return False 
        else:
              print "prime"
              return True
 is_prime(2)

#2

Two issues:
1)What is x % i == 0 doing? I'm guessing you wanted this to actually be a conditional statement. At the moment, count will always have 1 added to it.

 for i in range(2,9):
          x % i ==0
          count = count +1

2) On the first iteration of this loop you are checking if count ==2 or not and the returning True or False based on that. A return statement ends the function, so you will always get True because after 1 iteration count cannot equal 2. Think about the identation of the if else statement.

 for i in range(2,9):
          x % i ==0
          count = count +1
         if count == 2:
              print " non prime "
              return False 
        else:
              print "prime"
              return True

#3

We will want the range to include x

for n in range(2, x):

This way the limit is x - 1, and not a fixed value.

Using a count value is one approach, but on a large number the loop will have to iterate many times. Would it be simpler if a divisible value is immediately ejected and the function terminate?


#4

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