Python coding (prime numbers)?
Hello! I'm learning Python and thought I'd challenge myself to build an algorithm that generates all prime numbers up to a certain number Z, but for some reason it skips numbers like 3, and I don't understand why… Can you find the error?
The problem is that range at the beginning of the loop is always newly evaluated and is not fixed.
Thus, at the end of the loop for i=2 a=3. However, the range goes up to 3 and i is evaluated again for 3 . Then it is written to b[0]=3 since you previously deleted b[0] and b[1]. Then the loop ends with i=3 the range to end.
The simplest solution is a “break” at the end of if len(b)==2 or the range can only run until a.
Here the Debug edition and the problematic part highlighted.
Thank you.
You obviously start with 4, as a is initialized with 2 (a+1) then 3 and i+ is counted again before the first run:
I write here:
Then I get:
Interesting, the confused me now a bit because for i in range(3-as an example): 0-1-2 passes through thus 3 is never touched.(With i+=1 it is solved)1-2-3 and with i+=1 and a+=1 1-2-3-4 , but that should not be a problem because an a(modulo)i and i>a always gives a and thus=! 0 # c==0
So why does your code and mine not work?
I wrote to you how he works for me and how I immediately explained that i = … a+1 and then an i+=1 is too much. I didn’t get any more thoughts about it.
Your solution is good, but the problem analysis is not quite correct. In fact, the problem is that range is newly evaluated at the beginning of each loop and if a makes a step at the end of the loop is made an extra run for i=a, but the array is already emptied.