Is_prime section


#1

def is_prime(x):
  y = 2
  if x < 2:
      return False
  while y < x:
      if x % y == 0 :
          return False
      y += 1     
  else:     
      return True

the code above works perfectly but the thing is that, I didnt get why we are adding ( y += 1) in if statement. Code is not complete without it and fails to run.

Thanks in advance


#2

you use a while loop to iterate over the values between 2 and x, agree? y serves as your counter, you will have to increase. otherwise the condition will never be false, and you don't test all the numbers between 2 and x


#3

Well well, then we basicly show the code to which numbers to examine if they are prime or not, great.
Thank you very much!


#4

you're welcome, one one more piece of advice, you can add function call + print statements to see what your code is actually doing:

def is_prime(x):
  y = 2
  if x < 2:
      return False
  while y < x:
      print x, y
      if x % y == 0 :
          return False
      y += 1     
  else:     
      return True
print is_prime(9)

#5

def is_prime(x):
    if x<2:
        return False
    elif x==2:
        return True
    else:
        for n in range(2,x):
            if x%n==0:
                return False
            else:
                return True

could someone point our what is wrong with this code?
Many thanks


#6

well, in the first run of the for loop, either if is true, or else will execute, either way, a return keyword is reached in the first run of the loop causing the function to end.

you only want to return True after the loop has finished running, maybe you should change some indention somwhere?


#7

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