0

I have a simple problem: take a number and determine if it is prime. I cannot figure out why on earth the following does not work.

def prime(x):
    for i in range (2, x):
        if x % i == 0:
            return False 
        return True

prime(21)

This returns true! I have no idea why.

taurus05
  • 2,491
  • 15
  • 28
k.dav
  • 59
  • 1
  • 6
  • You need to let your loop run fully first before returning. It should be outside the for loop – kerwei Feb 01 '19 at 05:47
  • because `return`means end of the function - and in your case, this will happen already at `i==2`: returning `False` if `x % 2 == 0` and `True`otherwise. – SpghttCd Feb 01 '19 at 05:48

1 Answers1

1

In your code you have put return True inside the for loop, so it only checks whether the number is divisible by two and if not, it returns true.

Rather use this

def prime(x):
    for i in range (2, x):
        if x % i == 0:
            return False 
    return True

Also to improve efficiency a bit use for i in range (2, int(x/2)+1) since once you have reached x/2 no number after that can divide it anyhow.

In future try debugging your code by printing values of loop indexes where it defaults or using a debugger, it is real helpful and helps you improve as a programmer.

anand_v.singh
  • 2,768
  • 1
  • 16
  • 35