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?

(1 votes)
Loading...

Similar Posts

Subscribe
Notify of
6 Answers
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
TUrabbIT
4 months ago

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.

evtldocha
4 months ago

You obviously start with 4, as a is initialized with 2 (a+1) then 3 and i+ is counted again before the first run:

     for i in range (a+1):
       i+=1

I write here:

     for i in range (a):
       i+=1

Then I get:

user@system:~> python Primenumbers.py  
Limit z = 100
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97


evtldocha
4 months ago
Reply to  Thobias771

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.

TUrabbIT
4 months ago
Reply to  evtldocha

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.