Smallest Consecutive Four-Factor Composites
September 17, 2013
I found this problem on a discussion board for beginning programmers. It feels like a Project Euler problem, but I looked and didn’t find it there:
The smallest pair of consecutive natural numbers that each have two distinct prime factors are 14 = 2 * 7 and 15 = 3 * 5. The smallest triplet of consecutive natural numbers that each have three distinct prime factors are 644 = 2^2 * 7 * 23, 645 = 3 * 5 * 43 and 646 = 2 * 17 * 19. What is the smallest set of four consecutive natural numbers that each have four distinct prime factors?
Your task is to write a program that finds the set of four natural numbers. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Now try finding the smallest run of three consecutive numbers with exactly one prime factor. ;-)
Well, that didn’t quite work. Let’s try that again.
Related mathoverflow thread:
http://mathoverflow.net/questions/52417/consecutive-numbers-with-n-prime-factors
A version in Python. The generator fac_gen generates pairs (i, number of distinct factors of i) and is in principle unlimited, as long as it fits in memory. It works up to n=5.
A minor optimization to the posted fff2 which, instead of always incrementing the search loop by 1, skips ahead by up to 4 places based upon the values seen so far (inspired by KMP string search):
Under Kawa on my laptop, I see results like
Execution of (fff1) took 1995.53 ms
134043
Execution of (fff2 135000) took 87.817 ms
134043
Execution of (fff3 135000) took 66.956 ms
134043
Oops, that should be (let ((n-4 (- n 4))) … (if (> i n-4) …)) otherwise there can be an index out of bounds error.
I decided to see what kind of improvement there would be adding type info and using a primitive int array rather than a vector — this is still with Kawa — and it turns out to be quite substantial (another factor of 10):
Execution of (fff4 135000) took 6.586 ms
134043
A version of
fff2
in C++11, making use of my library that (sort of) implements Haskell’sMaybe
:Straightforward Racket version:
I also did a sieved version and one for n consecutive numbers with m total distinct prime factors (since that’s how I originally read the problem :) on my blog: jverkamp.com: Smallest Consecutive Four-Factor Composites