Home > Software design >  Prime Number with Simple for loop not working?
Prime Number with Simple for loop not working?

Time:02-22

Im trying to solve a problem where I have to use a for loop in solving if a number is prime or not. It seems like it only picks up if the number is divided by two to determine if it is prime or not. My code doesn't pick up if it is divisible by 3 and up though...

Here is my code:

def isPrime(num):
  for i in range (2,num):
    if (num%i) !=0:
      return True
    else:
      return False


isPrime(15)

I know 15 is not a prime number but it is returning True instead of False. Can anyone help? Thanks

CodePudding user response:

OP's algorithm always exits on the first iteration.

Instead, loop less often and only exit loop when a divisor is found. Also account for values less than 2.

def isPrime(num):
  for i in range [2,isqrt(num)]:
    if (num%i == 0) return False
  
  if (num < 2) return False
  return True
  • Related