I created a primality test algorithm, but it doesn't work.
In essence, these are the steps my program takes:
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 boundlower = 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!
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]