This is a code to find the prime factorization of consecutive numbers between 1 and n. It’s part of a larger program I’m working on. Since to find prime factorizations I only need to test for primes, for each number, starting from 1, in this program I check to see if the number is divisible by any of the primes in the primes list. If not, then it is added to the primes list. This way each larger number builds off previous primes found. Is there a way to make this algorithm faster?
primes = []
def factorize(n):
global primes; global primitivesp_nos; x = []
for i in primes:
while n % i == 0: x.append(i); n = n//i
if i * i > n: break
if n > 1: x.append(n)
if len(x) == 1: primes.append(x[0])
return x
print([factorize(i) for i in range(1, 10)])
#Output: [[], [2], [3], [2, 2], [5], [2, 3], [7], [2, 2, 2], [3, 3]]