Not surprised on the lack of result for N=4, performing a linear extrapolation of the comparisons on the 1.7 seconds leads to about 10 hours. (41,314 for N=3 vs. 880,972,037 comparisons for N=4).

I created a priority queue based version last night, but I tickled Rakudo the wrong way with my implementation and it was very slow (heaps are pretty simple, they pretty much just need push, pop, and swap to be fairly fast operations on the list type). It may still end up faster for N=4 because 10 hours is not a hard time to beat, but N=3 was about 5-10 times slower using it. I’ll see if I can get it running faster, perl 6 should have a priority queue module implemented for it anyways, so it will be good to have either way.

]]>Anyway, I ran your algorithm on my machine and it clocks in at 1.7s for N=3. For N=4, I stopped the run after ~40m without result.

If you have a github account, feel free to add your code to the repository – as-is or after making the suggested improvements.

]]>Like anything, you flip the problem onto it’s head. Instead of factoring the number, you work from the fact you are going through these numbers in sequence and essentially write a sieve of Eratosthenes that keeps track of how many primes cross out a number.

Slow version that uses a list instead of a priority queue is https://gist.github.com/4200603

(The essential difference with the priority queue is that you pop off all the items with key == $_, then push them back on with the updated number).

To reduce churn in the data structure, you’d probably also want to just keep 2 and 3 as separate counters because they come up so often.

I have a very old version of perl6 at work, so I can’t really give you speed numbers. But the c version of the same algorithm is in the less than a second category for N = 4, even without a priority queue.

]]>