astrae
astrae

Reputation: 63

Python prime list

integer = int(input("Enter an integer: "))
if integer >= 2:
    print(2)
for i in range(2, integer + 1): # range 2,3,...,integer (excludes 1)
    for j in range(2, i): # we are going to try dividing by these
        if i % j == 0: # not prime
            break
        else: # is prime
            print(i)

input:

7

output:

2
3
5
5
5
7
7
7
7
7

output I want:

2
3
5
7

adding more detail to get past error:

It looks like your post is mostly code; please add some more details.

Upvotes: 1

Views: 87

Answers (3)

Abhishek Bhagate
Abhishek Bhagate

Reputation: 5766

Your logic is slightly wrong. I have added the correct code below with comments :

integer = int(input("Enter an integer: "))

if integer >= 2:
    print(2)

for i in range(2, integer + 1): # range 2,3,...,integer (excludes 1)
    prime=true                       #assume that i is prime
    for j in range(2, i):       # we are going to try dividing by these
        if i % j == 0:          # not prime
            prime=false             # we now know it is not prime
            break
    if prime==true:                # if we didn't do prime=0, then it's a prime
        print(i)

What you were doing is printing i for every j from 2 to i that did not divide i. But instead, what had to be done is print i only once when none of the j from 2 to i divided i.

Hope you understand the mistake and this clears your doubt !

Upvotes: 1

Varun Nayak
Varun Nayak

Reputation: 310

Put the print(i) in the outer for loop with a flag that keeps track of the result.

for i in range(2, integer + 1): # range 2,3,...,integer (excludes 1)
    isPrime = True
    for j in range(2, i): # we are going to try dividing by these
        if i % j == 0:
            isPrime = False
            break
    if isPrime:
        print(i)

Upvotes: 2

Barmar
Barmar

Reputation: 781058

You're printing i for every value of j that doesn't divide it, until you get a value that does divide it and you execute break.

You should only print i when you don't break out of the loop. Put the else: statement on the for loop, not if. This else: statement is executed when the loop finishes normally instead of breaking.

for i in range(2, integer + 1): # range 2,3,...,integer (excludes 1)
    for j in range(2, i): # we are going to try dividing by these
        if i % j == 0: # not prime
            break
    else: # is prime
        print(i)

Upvotes: 5

Related Questions