Mar-20-2020, 05:21 AM
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_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)