Skip to content

Instantly share code, notes, and snippets.

@abecus
Created August 26, 2020 19:14
Show Gist options
  • Save abecus/685937c229f3ac84955814f20a191012 to your computer and use it in GitHub Desktop.
Save abecus/685937c229f3ac84955814f20a191012 to your computer and use it in GitHub Desktop.
from math import ceil, sqrt
def EratosthenesSieve(N:int)-> list:
'''
Calculating SPF (Smallest Prime Factor) for every number till N.
Time Complexity : O(NloglogN)
'''
N+=1
# stores smallest prime factor for every number
spf = [*range(N)]
# separately marking spf for every even number as 2
for i in range(4, N, 2):
spf[i] = 2
for i in range(3, ceil(sqrt(N))):
# checking if i is prime
if (spf[i] == i):
# marking SPF for all numbers divisible by i
for j in range(i * i, N, i):
# marking spf[j] if it is not previously marked
if (spf[j] == j):
spf[j] = i
return spf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment