Problem 308: An amazing Prime-generating Automaton

A program written in the programming language Fractran consists of a list of fractions.

The internal state of the Fractran Virtual Machine is a positive integer, which is initially set to a seed value.
Each iteration of a Fractran program multiplies the state integer by the first fraction in the list which will leave it an integer.

For example, one of the Fractran programs that John Horton Conway wrote for prime-generation consists of the following 14 fractions:

The powers of 2 that appear in this sequence are 2^2, 2^3, 2^5, ...
It can be shown that all the powers of 2 in this sequence have prime exponents and that all the primes appear as exponents of powers of 2, in proper order!

If someone uses the above Fractran program to solve Project Euler Problem 7 (find the 10001st prime), how many iterations would be needed until the program produces 2^{10001st \space prime} ?

My Algorithm

The crucial discovery is that all fractions can be factorized such that the largest prime factor is 29 and no prime appears as a square (or cube).
The sequence becomes:

The 10001st prime needs 10001 bits to be represented - way beyond the 64 bits of unsigned long long.
However, I can factorize the current number as well and it's initial value is 2 = 2^1.
I could include all the other (non-existing) prime factors, too, so that2 = 2^1 * 3^0 * 5^0 * 7^0 * 11^0 * 13^0 * 17^0 * 19^0 * 23^0 * 29^0

Each fraction increments or decrements some exponents. No exponent must become negative because then it wouldn't be an integer anymore.
Whenever all exponents except the exponent of 2 are zero, then I found another prime and it's the exponent of 2.

I wrote a brute-force function enumerate() that finds the 100th prime in a few seconds (matching the values of OEIS A007547).
But more important, I included a "visualization" of each step which revealed:

the exponents of 2, 3, 5, 7 change a lot, often they are incremented or decremented

the exponents of 11, 13, 17, 19, 23, 29 never exceed 1

actually at most one of the exponents of 11, 13, 17, 19, 23, 29 is 1 and all the others are zero

These are the 19 steps for the first prime (I replaced zeros by an underline to emphasize the patterns):

My function search() is build on these properties. It's a state machine which has 7 states S_, S11, S13, S17, S19, S23 and S29
(where the number after S indicates the exponent which is currently 1 or S_ if all are zero, which is the default state, too).

The 14 fractions can be interpreted as:

dfrac{17}{91} = dfrac{17}{7 * 13} → when in state S13 then try to decrement the exponent of 7 and continue in state S17

dfrac{78}{85} = dfrac{2 * 3 * 13}{5 * 17} → when in state S17 then try to decrement the exponent of 5, increment the exponents of 2 and 3 and continue in state S13

dfrac{19}{51} = dfrac{19}{3 * 17} → when in state S17 then try to decrement the exponent of 3 and continue in state S19

... and so on. The current state is in the denominator and the follow-up state in the numerator.
Any prime factors 2, 3, 5, 7 found in the numerator are incremented but if found in the denominator then they are decremented.

That state machine is substantially faster than the previously mentioned enumerate() function.
It needs about 10 seconds to find the first 500 prime numbers but then becomes slower and slower (because the number of steps seems to grow exponentially).

However, I saw a few patterns in the output of enumerate() that allow me to "merge" states:
depending on the current state s_i and the exponents of 2, 3, 5, 7, the follow-up state s_{i+1} might return to the previous state s_i (while modifying the exponents of 2, 3, 5, 7).
Look for the #ifdef OPTIMIZE pragmas to locate my optimizations.

The first optimization can be found in state S11:

if the exponent of 3 is positive (three > 0), then it's decremented and followed by state S29

state S29 increments the exponent of 7 and returns to state S11

→ that's a simple loop which simplifies to seven += three; three = 0;
→ the total number of steps would be 2 * three (visit S11 and S29 once per iteration)
→ this optimization saves about 1/3 of all steps (143,165,562 iterations to count the 213,945,763 steps for the first 100 primes)

The second optimization can be found in state S13:

if the exponents of 5 and 7 are both positive (seven > 0 && five > 0), then both are decremented and followed by state S17

state S17 increments the exponents of 2 and 3, decrements the exponent of 5 and returns to state S13

→ that's another loop which stops whenever five or seven becomes zero
→ there are std::min(five, seven) iterations of that loop and each requires 2 steps
→ saves about 1/3 (143,263,171 iterations to process the 213,945,763 steps for the first 100 primes)
→ saves about 2/3 together with the first optimization (72,482,969 iterations to count the 213,945,763 steps for the first 100 primes)

I was surprised that these two optimization are sufficient to solve the problem (10001th prime):
the result is a number with 16 digits and found in about a minute but according to my logging the program processed 513,273,040,838,264 iterations.
That's impossible - the code runs on a modest Core i7 CPU which is clocked somewhere between 3 and 4 GHz (depending on overall load).
Even the best-case scenario would mean that roughly 250 * 10^9 CPU cycles were "burnt" while processing 513 * 10^12 iterations - that's 2000 iterations per CPU cycle !!!

Clearly the GCC compiler found some optimization that I missed. And after a few minutes I stumbled across it (and it's so simple I wonder why I didn't spot it earlier).
The third optimization was hidden in state S19 and its structure is similar to the first optimization:

if the exponent of 2 is positive (two > 0), then it's decremented and followed by state S23

state S23 increments the exponent of 5 and returns to state S19

→ that's a simple loop which simplifies to five += two; two = 0;
→ the total number of steps would be 2 * two (visit S19 and S23 once per iteration)
→ saves about 1/3 (143,313,579 iterations to process the 213,945,763 steps for the first 100 primes)

And now comes the incredible part:
if all three optimzations are enabled simultaneously then the total number of iterations needed to figure out the number of steps quickly drops to less than 1%:
1,850,784 iterations are sufficient to process the 213,945,763 steps for the first 100 primes (that's 0.865%, or put in another way, I saved 99.135%).
And 76 * 10^9 iterations to know that it takes 1.5 * 10^15 steps (i.e. saved 99.9950278%) to find the 10001th prime.
By the way: that's only 2 CPU cycles per iteration, so there's still "something going on" in the GCC optimizer ...

The execution time didn't drop when I added that third optimization (because GCC discovered it anyway)
but other C++ compilers with less smart optimizer should now be able to emit reasonably fast code, too.

Alternative Approaches

The Project Euler forum is full of other optimizations which aren't as simple as mine.
The fastest programs solve the problem in less than a second.

Note

Another tough lesson in how modern software can almost outsmart a human being ...

The source code doesn't need anything from my toolbox and is one of the longest with "original" code written specificly to solve only one problem.

Interactive test

You can submit your own input to my program and it will be instantly processed at my server:

Input data (separated by spaces or newlines):

This is equivalent toecho 10 | ./308

Output:

(please click 'Go !')

Note: the original problem's input 10001cannot be enteredbecause just copying results is a soft skill reserved for idiots.

(this interactive test is still under development, computations will be aborted after one second)

My code

… was written in C++11 and can be compiled with G++, Clang++, Visual C++. You can download it, too.

#include<iostream>

#include<iomanip>

#include<algorithm>

// slowly step through all iterations until enough primes are found; display the exponents in each step

Those links are just an unordered selection of source code I found with a semi-automatic search script on Google/Bing/GitHub/whatever.
You will probably stumble upon better solutions when searching on your own.
Maybe not all linked resources produce the correct result and/or exceed time/memory limits.

Heatmap

Please click on a problem's number to open my solution to that problem:

green

solutions solve the original Project Euler problem and have a perfect score of 100% at Hackerrank, too

yellow

solutions score less than 100% at Hackerrank (but still solve the original problem easily)

gray

problems are already solved but I haven't published my solution yet

blue

solutions are relevant for Project Euler only: there wasn't a Hackerrank version of it (at the time I solved it) or it differed too much

orange

problems are solved but exceed the time limit of one minute or the memory limit of 256 MByte

red

problems are not solved yet but I wrote a simulation to approximate the result or verified at least the given example - usually I sketched a few ideas, too

black

problems are solved but access to the solution is blocked for a few days until the next problem is published

[new]

the flashing problem is the one I solved most recently

I stopped working on Project Euler problems around the time they released 617.

The 310 solved problems (that's level 12) had an average difficulty of 32.6&percnt; at Project Euler and
I scored 13526 points (out of 15700 possible points, top rank was 17 out of &approx;60000 in August 2017)
at Hackerrank's Project Euler+.

My username at Project Euler is stephanbrumme while it's stbrumme at Hackerrank.

Copyright

I hope you enjoy my code and learn something - or give me feedback how I can improve my solutions.All of my solutions can be used for any purpose and I am in no way liable for any damages caused.You can even remove my name and claim it's yours. But then you shall burn in hell.

The problems and most of the problems' images were created by Project Euler.Thanks for all their endless effort !!!

more about me can be found on my homepage,
especially in my coding blog.
some names mentioned on this site may be trademarks of their respective owners.
thanks to the KaTeX team for their great typesetting library !