Search code examples
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:

  • Ask the user for a lower and upper bound in which to look for primes
  • An array, primes, will store my primes
  • A nested for loop; the first for loop takes every number between the user's lower and upper bounds and then checks if every one of those numbers is divisible by any of the numbers between 2 and the user's upper bound
  • If any number between the lower and upper bounds is divisible by any number between 2 and the user's upper bound, the number is obviously not prime.
  • Otherwise, the number is appended to the array primes:
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]