Problem #47 is one of the many Project Euler problems that involves prime numbers. The problem reads:
Project Euler Problem 47: Distinct primes factors
The first two consecutive numbers to have two distinct prime factors are:
14 = 2 × 7
15 = 3 × 5
The first three consecutive numbers to have three distinct prime factors are:
644 = 2² × 7 × 23
645 = 3 × 5 × 43
646 = 2 × 17 × 19.
Find the first four consecutive integers to have four distinct prime factors each. What is the first of these numbers?
As you can probably guess, my solution involves iterative brute force. Here is my solution:
Solution #1: Brute Force Approach
We simply iterate through all the numbers, counting the number of factors of each one while maintaining a “streak” counter of consecutive numbers with exactly 4 factors. When counting the prime factors of a number, once 5 factors have been counted, we can stop counting. In addition, all prime factors can be divided out once found to reduce the size of the number that needs to be factored. Here is an implementation of this approach in Python 2.7:
'''
Author: Walker Kroubalkian
Brute Force Approach to Project Euler Problem #47
'''
import time
from math import sqrt
def countPrimes(n,k):
total = 0
if(n%2==0):
total+=1
while(n%2==0):
n/=2
c = 3
while(c<=sqrt(n)):
if(n%c==0):
total+=1
if(total>k):
return False
while(n%c==0):
n/=c
c+=2
if(n>1):
total+=1
return total == k
def projectEulerProblemFortySeven(n,k):
c = 14
streak = 0
while(streak<n):
if(countPrimes(c,k)):
streak+=1
if(streak==n):
return (c-n+1)
else:
streak = 0
c+=1
return "HOW"
start = time.time()
print projectEulerProblemFortySeven(4, 4)
print ("--- %s seconds ---" % (time.time()-start))
'''
Prints
134043
--- 0.572690010071 seconds ---
for input of n = 4, k = 4
'''
As shown above, brute force can be quite effective. I am sure that there is a more efficient solution to this problem, and I may come back to look for a more efficient approach later.
Thanks for reading! See you tomorrow.