Where to start?
You're editing a list while iterating over it. That is generally ill
advised -- weird bugs can come of it.
You increment num
no matter what happens in your condition -- this is your main issue
you're checking every number between the first and last primes you've found, not just the primes
here is a fix of your code
def print_primes_to(n):
primes = [2,3]
for prime in primes:
print(prime)
for num in range(5, n, 2):
isprime = True
for prime in primes:
if num % prime == 0: #not prime
isprime = False
break
if isprime: # could replace with for/else
primes.append(num)
print(num)
test case
>>> print_primes_to(30)
2
3
5
7
11
13
17
19
23
29
There are better algorithms, here is one I have lying around:
import itertools as _itertools
def primelist(n):
"""Returns a list of all primes less than n."""
if n <= 2:
return []
nums = [True]*(n - 2)
for num in range(2, _rootp1(n)):
for counter in _itertools.count(num):
product = counter * num
if product >= n:
break
nums[product - 2] = False
return [index for index, val in enumerate(nums, 2) if val]
def _rootp1(n: float) -> int:
"""returns the truncated square root of n plus 1 for use in range"""
return int(n**0.5) + 1
See how long it takes to generate all primes less that 1 million
%timeit primelist(1_000_000)
1.33 s ± 30.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)