Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Prime Number with Simple for loop not working?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading