1 ! Copyright (c) 2008 Aaron Schaefer.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: arrays kernel math math.primes math.primes.factors
4 ranges namespaces sequences project-euler.common ;
7 ! http://projecteuler.net/index.php?section=problems&id=47
12 ! The first two consecutive numbers to have two distinct prime factors are:
17 ! The first three consecutive numbers to have three distinct prime factors are:
23 ! Find the first four consecutive integers to have four distinct primes
24 ! factors. What is the first of these numbers?
30 ! Brute force, not sure why it's incredibly slow compared to other languages
34 : (consecutive) ( count goal test -- n )
38 dup prime? [ [ drop 0 ] 2dip ] [
39 2dup unique-factors length = [ [ 1 + ] 2dip ] [ [ drop 0 ] 2dip ] if
40 ] if 1 + (consecutive)
43 : consecutive ( goal test -- n )
44 0 -rot (consecutive) ;
48 : euler047 ( -- answer )
52 ! 344688 ms run / 20727 ms GC time
58 ! Use a sieve to generate prime factor counts up to an arbitrary limit, then
59 ! look for a repetition of the specified number of factors.
65 : initialize-sieve ( n -- )
66 0 <repetition> >array sieve set ;
68 : is-prime? ( index -- ? )
71 : multiples ( n -- seq )
72 sieve get length 1 - over <range> ;
74 : increment-counts ( n -- )
75 multiples [ sieve get [ 1 + ] change-nth ] each ;
77 : prime-tau-upto ( limit -- seq )
78 dup initialize-sieve 2 swap [a..b) [
79 dup is-prime? [ increment-counts ] [ drop ] if
82 : consecutive-under ( m limit -- n/f )
83 prime-tau-upto [ dup <repetition> ] dip subseq-start ;
87 : euler047a ( -- answer )
88 4 200000 consecutive-under ;
90 ! [ euler047a ] 100 ave-time
91 ! 331 ms ave run time - 19.14 SD (100 trials)
93 ! TODO: I don't like that you have to specify the upper bound, maybe try making
94 ! this lazy so it could also short-circuit when it finds the answer?