Python Forum
Trouble interpreting prime number code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Trouble interpreting prime number code
#1
The assignment is to write a function that returns the number of prime numbers that exist up to and including a given number. The solution is below but I'm having trouble interpreting it. The part I don't understand is the 'for y in range(3,x,2)' loop. The first time it runs, x = 3 so I see it as 'range(3,3,2) but this doesn't make sense because the middle number represents up to but not including. So a range of 3-2 doesn't make sense. Also why is 'else:' not lined up with 'if'?

def count_primes(num):
primes = [2]
x = 3
if num < 2: # for the case of num = 0 or 1
return 0
while x <= num:
for y in range(3,x,2): # test all odd factors up to x-1
if x%y == 0:
x += 2
break
else:
primes.append(x)
x += 2
print(primes)
return len(primes)

def count_primes2(num):
primes = [2]
x = 3
if num < 2:
return 0
while x <= num:
for y in primes: # use the primes list!
if x%y == 0:
x += 2
break
else:
primes.append(x)
x += 2
print(primes)
return len(primes)

def count_primes2(num):
    primes = [2]
    x = 3
    if num < 2:
        return 0
    while x <= num:
        for y in primes:  # use the primes list!
            if x%y == 0:
                x += 2
                break
        else:
            primes.append(x)
            x += 2
    print(primes)
    return len(primes)
Reply
#2
range(3, x, 2) returns an iterable beginning with 3 and ending at x. The third argument is the "step" which instructs how to calculate the next value. So, range(3, 12, 2) would include 3, 5, 7, 9, 11.

The "else" is used with the for loop. That block executes once the for loop has completed per the documentation.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Trying to find the next prime number FirstBornAlbratross 8 4,242 Aug-14-2023, 01:16 PM
Last Post: deanhystad
  Interpreting this code EmBeck87 4 1,523 Apr-10-2023, 12:40 PM
Last Post: EmBeck87
  calculate the 10001st prime number topologh 7 6,196 Oct-05-2020, 07:41 PM
Last Post: deanhystad
  Prime number code ryfoa6 3 2,882 Mar-21-2020, 12:23 AM
Last Post: ryfoa6
  Asking for help in my code for a "Guess the number" game. Domz 5 3,780 Aug-14-2019, 12:35 PM
Last Post: perfringo
  Prime number Python homework mkrisz98 11 5,572 May-10-2019, 05:23 PM
Last Post: mkrisz98
  Help interpreting code schniefen 1 2,032 May-03-2019, 05:23 PM
Last Post: ichabod801
  how to find a next prime number? iamyourfather 2 6,501 Oct-01-2017, 04:21 PM
Last Post: gruntfutuk

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020