pythonalgorithmnumbersprimesprimality-test

Primality Test algorithm fails


I created a simple primality test algorithm, but it fails for numbers like 15. Why?

number = int(input("Test if Prime: "))

print ("Is " + str(number) + " Prime?: ")

for i in range (2, number): 
  if number % i == 0: 
    print ("No")
    break
  else: 
    print ("Yes")

I tried an elif statement with other variations, but it still doesn't work:

number = int(input("Test if Prime: "))

print ("Is " + str(number) + " Prime?: ")

for i in range (2, number): 
  if number % i == 0: 
    break
  elif number % i != 0: 
    print ("Yes")

Any help is appreciated.


Solution

  • You have your else condition inside the loop. At any point in time, it'll only check for one value...

    Modifying your for loop to print out the number it is checking for:

    for i in range (2, number): 
      print (i)
      if number % i == 0: 
        print ("No")
        break
      else: 
        print ("Yes")
    

    prints out (for number = 15):

    2
    Yes
    3
    No
    

    Which you know works if it prints out 'No' number - 1 times

    To slightly modify what you did, we can just change it to:

    flag = False
    for i in range (2, number): 
      if number % i == 0: 
        print ("No")
        flag = True
        break
    if (!flag)
      print("Yes")
    

    All this does is push the print statement outside the loop (for a number to be prime it needs to be non-divisible by all numbers less than it). The flag ensures that you only print out True or False (you don't want to print out both)