Skip to content

Instantly share code, notes, and snippets.

@PM2Ring
Created April 18, 2022 12:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PM2Ring/31d1fc471f83ab2a3e2482ef4dc15543 to your computer and use it in GitHub Desktop.
Save PM2Ring/31d1fc471f83ab2a3e2482ef4dc15543 to your computer and use it in GitHub Desktop.
Find all divisors in a range by sieving
#!/usr/bin/env python3
''' Find all divisors in a range by sieving
Written by PM 2Ring 2017.05.03
Prime GP version
'''
from itertools import product
from functools import lru_cache
def lowest_prime_factors(n):
s = [[1, i] for i in range(n)]
for i in range(int(n**0.5), 1, -1):
t = s[i]
if t[1] == i:
j = i
while j < n:
s[j : n : j] = [t] * ((n - 1) // j)
j *= i
t = t + [j]
return s
@lru_cache(None)
def divisors(j):
result = a[j]
j //= result[-1]
if j > 1:
result = [u*v for u, v in product(divisors(j), result)]
result.sort()
return result
n = 50
a = lowest_prime_factors(n)
for i in range(2, n):
t = divisors(i)
print(f'{i:2}: {t}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment