Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

> 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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading