-2

I made this prime number generator but it just prints every number (1, 2, 3...).

I am aware that there are other questions about this but I don't understand any of them. Here is what I have so far:

x = 1
y = 1
    while x >= y:
        if x % y == 0:
            print(x)
            x = x + 1
            y = 1
        else:
            y = y + 1
y = 1
Faradrim
  • 21
  • 2
  • 1
    Every number mod 1 is 0. The `else` is never reached and `y` is never updated. – Moses Koledoye Oct 07 '17 at 12:47
  • 1
    Also, your algorithm is quite broken. You're printing x when it has a multiple, not when you've checked every number and concluded that it doesn't have a multiple. You just need to review the standard algorithm. – Carcigenicate Oct 07 '17 at 12:47
  • I've fixed the indentation. It now looks how it does in my code – Faradrim Oct 07 '17 at 12:47
  • `x` and `y` should start from `2` at least right? – Sraw Oct 07 '17 at 12:48
  • Possible duplicate of [Python Prime Number Generator](https://stackoverflow.com/questions/30143643/python-prime-number-generator) – glennsl Oct 07 '17 at 12:56

2 Answers2

0

There's something called a rubber ducky test where you explain your code, step by step, to a rubber duck. It forces you to walk through every step and you'll often find the error. In this case, think about what y is when you do x%y. You'll see that y=1 the first time this is called. So it will iterate through the loop incrementing x by 1 and y will remain set it 1. And x%y when y=1 will always be...

jss367
  • 4,759
  • 14
  • 54
  • 76
0

From your question, I think, it would be better try this way :

n = 10
i = 2
while i < n :
    prime = 1 # reset the `prime` variable before the inner loop
    for a in range(2, i):
        if i%a == 0:
            prime = 0
            break
    if prime:    
        print (i)
    i += 1 

Output :

2
3
5
7
Md. Rezwanul Haque
  • 2,882
  • 7
  • 28
  • 45