pythonalgorithmnumbersprimesprimality-test

Using nested for loops to generate primes


I created a primality test algorithm, but it doesn't work.

In essence, these are the steps my program takes:

lower = int(input("Lower Bound: "))
upper = int(input("Upper Bound: "))

print ("Primes between " + str(lower) + " and " + str(upper) + ": ")

primes = []

for i in range (lower, upper): 
  for num in range (2, upper/2):
    if i % num == 0: 
      print (str(i-(lower-1)) + ". " + str(i) + " = No")
      break
  else: 
    primes.append(i)

print(primes)

However, the regardless whether a number is prime or not, the function always outputs no, but I have no idea why!


Solution

  • Fixed it. First, I did the floor division // operator so it returns an integer. Also, I made a condition that the divisor couldn't be divided by itself. Because otherwise 4 would be a prime of 4.

    lower = int(input("Lower Bound: "))
    upper = int(input("Upper Bound: "))
    
    print ("Primes between " + str(lower) + " and " + str(upper) + ": ")
    
    primes = []
    
    for i in range (lower, upper):
      for num in range (2, upper//2):
        if i % num == 0 and num != i: # modification here
          print (str(i-(lower-1)) + ". " + str(i) + " = No")
          break
      else:
        primes.append(i)
    
    print(primes)
    

    Out[1]: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43]