Search code examples
pythonprimes

Python program to find all prime numbers in the range 1 - n


Hi I know there are lots of solutions to this problem but I wanted some help finding out why my answer is wrong.

Here's my answer:

number = int(input("enter a number: "))

for n in range(2, number + 1):
    for i in range(2, number // 2):
        if n == 2:
            print(n)
        elif n % i == 0:
            break
        else:
            print(n)

Here's the output on my terminal:

> enter a number: 12 
  2 2 2 2 3 5 5 5 7 7 7 7 9 11 11 11 11

thankss


Solution

  • The problem with your solution is that you haven't set up the inner loop properly. The other problem (the lesser one in my opinion) is that the print is inside of your inner loop which causes the multiple prints.

    Here is a proper solution:

    for n in range(2, number + 1):
        isPrime = True
        for i in range(2, n - 1):
            if n % i == 0:
                isPrime = False
        if isPrime:
            print(n)