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

Why does using for loop for finding prime number runs only runs once?

I want to find the prime numbers up to the given number but my loop only runs once and my output is only 2 and 3, where did I went wrong?

def primer_check(n):
    prime_state = True
    for i in range(2,n+1):
        if i == 2:
            print(2)
            continue
        for j in range(2,i):
            if i % j == 0:
                prime_state = False
                break
        if prime_state: print(i)

n = int(input("Enter a number to see the prime numbers up to that number : "))
primer_check(n)

>Solution :

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

you have to set prime_state to True everytime when you start a new loop.here is the code.you are almost correct .Hope it helps 🙂

def primer_check(n):
    for i in range(2,n+1):
        prime_state = True
        if i == 2:
            print(2)
            continue
        for j in range(2,i):
            if i % j == 0:
                prime_state = False
                break
        if prime_state: print(i)
n = int(input("Enter a number to see the prime numbers up to that number : "))
primer_check(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