Find the first four consecutive integers to have four distinct prime factors each. What is the first of these numbers?
This is my solution for problem 47 on Project Euler.
def primes2(n):
""" Input n>=6, Returns a list of primes, 2 <= p < n """
n, correction = n-n%6+6, 2-(n%6>1)
sieve = [True] * (n//3)
for i in range(1,int(n**0.5)//3+1):
if sieve[i]:
k=3*i+1|1
sieve[ k*k//3 ::2*k] = [False] * ((n//6-k*k//6-1)//k+1)
sieve[k*(k-2*(i&1)+4)//3::2*k] = [False] * ((n//6-k*(k-2*(i&1)+4)//6-1)//k+1)
return [2,3] + [3*i+1|1 for i in range(1,n//3-correction) if sieve[i]]
def findSeq(lst):
""" Returns the index of the first term of a 4 term arithmetic sequence """
for x in range(len(lst)-2):
if sum(lst[x:x+4]) == (4*lst[x]+6):
return x
return False
def generateFactors(num,values,factors):
if len(values[num]) > 0:
factors += values[num]
return factors
else:
for i in range(2,num-1):
if num % i == 0:
return generateFactors(num//i,values,factors+[i])
n = 200000
primes = set(primes2(n))
factors = dict([[x,[]] for x in range(2,n)])
for item in factors.keys():
if item in primes:
factors[item] = [item]
else:
factors[item] = generateFactors(item,factors,[])
fourFact = [item for item in factors.keys() if len(set(factors[item])) == 4]
pos = findSeq(fourFact)
print(fourFact[pos])
The primes2 function isn't my code but I have included it for completeness. I am looking for feedback on my implementation and how to optimise the code.