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

wanted to have a single list instead of multiple list showing prime numbers

I tried to make a program that shows all prime number till the limit
but the code shows each factor adding to the ans list.
How do I fix this?

limit = 34
num = [value for value in range(2, limit + 1)]
factor = 2
ans = []
while True:
    if factor not in num:
        factor += 1
    elif factor in num:
        ans.append(factor)
        for ele in num:
            if ele % factor == 0:
                num.remove(ele)
        print(ans)

Expected Output

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]

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

>Solution :

You need to ensure the factor variable is bounded.

limit = 34
num = list(range(2, limit + 1))
factor = 2
ans = []
while factor <= limit+1:
    if factor not in num:
        factor += 1
    elif factor in num:
        ans.append(factor)
        for ele in num:
            if ele % factor == 0:
                num.remove(ele)
print(ans)
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