1

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')
User9102d82
  • 1,172
  • 9
  • 19
Priyanshu
  • 33
  • 4
  • for each `i`, for some `j` it will hold that `l1[i] == j` so for sure `l1[i] % j = 0`. I think you would want `j` to go **up until** `l1[i]` – Tomerikoo Feb 03 '20 at 18:16
  • @Tomerikoo so can you teach me the correct code for this? – Priyanshu Feb 03 '20 at 18:20
  • 1
    There are many (many) resources online dealing with finding prime numbers. I am sure you will be able to find some useful ones to help you get the hang of it – Tomerikoo Feb 03 '20 at 18:23
  • I think this might help you https://en.wikipedia.org/wiki/Primality_test – imbr Feb 03 '20 at 19:01

1 Answers1

0

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

vincentlc
  • 1
  • 1