I want a list of n
numbers and check each item for primality and log whether the given number is prime or not. Unfortunately my below shown code is working incorrectly and I need help finding out why is it happening.
My code snippet:
l1 = []
num = int(input("Enter a range of numbers :: "))
for i in range(2, num + 1):
l1.append(i)
for i in range(0, num - 1):
for j in range(2, num):
if l1[i] % j == 0:
print(f'{l1[i]} is not a prime ')
break
else:
print(f'{l1[i]} is a prime number')
The solution is to do the loop that check if the number is prime for
for j in range(2, l1[i]):
Because here num have nothing to do with the check if it's prime. So the complete code is :
l1 = []
num = int(input("Enter a range of numbers :: "))
for i in range(2, num + 1):
l1.append(i)
for i in range(0, num - 1):
for j in range(2, l1[i]):
if l1[i] % j == 0:
print(f'{l1[i]} is not a prime ')
break
else:
print(f'{l1[i]} is a prime number')
For more info about algorithm to check if a number is prime, please refer to : this post
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.