Improve solution for problem 47

This commit is contained in:
2019-09-28 11:31:06 +02:00
parent ed7031df4d
commit 7489196be8
2 changed files with 64 additions and 90 deletions

View File

@ -14,65 +14,46 @@
# Find the first four consecutive integers to have four distinct prime factors each. What is the first of these numbers?
from timeit import default_timer
from projecteuler import sieve
def count_distinct_factors(n):
global primes
count = 0
# Function using a modified sieve of Eratosthenes to count
# the prime factors of each number.
def count_factors(n):
factors = [0] * n
i = 2
# Start checking if 2 is a prime factor of n. Then remove
# all 2s factore.
if n % 2 == 0:
count = count + 1
while i < n // 2:
if factors[i] == 0:
for j in range(i, n, i):
factors[j] = factors[j] + 1
i = i + 1
while True:
n = n // 2
if n % 2 != 0:
break
i = 3
# Check all odd numbers i, if they're prime and they're a factor
# of n, count them and then divide n for by i until all factors i
# are eliminated. Stop the loop when n=1, i.e. all factors have
# been found.
while n > 1:
if primes[i] == 1 and n % i == 0:
count = count + 1
while True:
n = n // i
if n % i != 0:
break
i = i + 2
return count
return factors
def main():
start = default_timer()
global primes
N = 150000
primes = sieve(N)
found = 0
i = 647
factors = count_factors(N)
# Starting from 647, count the distinct prime factors of n, n+1, n+2 and n+3.
# If they all have 4, the solution is found.
while not found and i < N - 3:
if primes[i] == 0 and primes[i+1] == 0 and primes[i+2] == 0 and primes[i+3] == 0:
if count_distinct_factors(i) == 4 and count_distinct_factors(i+1) == 4 and count_distinct_factors(i+2) == 4 and count_distinct_factors(i+3) == 4:
found = 1
i = i + 1
count = 0
# Find the first instance of four consecutive numbers
# having four distinct prime factors.
for i in range(N):
if factors[i] == 4:
count = count + 1
else:
count = 0
if count == 4:
res = i - 3
break
end = default_timer()
print('Project Euler, Problem 47')
print('Answer: {}'.format(i-1))
print('Answer: {}'.format(res))
print('Elapsed time: {:.9f} seconds'.format(end - start))