1 ! Copyright (c) 2008 Aaron Schaefer.
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: arrays kernel math math.primes math.primes.factors ranges
4 namespaces sequences project-euler.common ;
7 ! https://projecteuler.net/problem=47
12 ! The first two consecutive numbers to have two distinct prime
18 ! The first three consecutive numbers to have three distinct
25 ! Find the first four consecutive integers to have four distinct
26 ! primes factors. What is the first of these numbers?
32 ! Brute force, not sure why it's incredibly slow compared to
37 : (consecutive) ( count goal test -- n )
41 dup prime? [ [ drop 0 ] 2dip ] [
42 2dup unique-factors length = [ [ 1 + ] 2dip ] [ [ drop 0 ] 2dip ] if
43 ] if 1 + (consecutive)
46 : consecutive ( goal test -- n )
47 0 -rot (consecutive) ;
51 : euler047 ( -- answer )
55 ! 344688 ms run / 20727 ms GC time
61 ! Use a sieve to generate prime factor counts up to an arbitrary limit, then
62 ! look for a repetition of the specified number of factors.
68 : initialize-sieve ( n -- )
69 0 <repetition> >array sieve set ;
71 : is-prime? ( index -- ? )
74 : multiples ( n -- seq )
75 sieve get length 1 - over <range> ;
77 : increment-counts ( n -- )
78 multiples [ sieve get [ 1 + ] change-nth ] each ;
80 : prime-tau-upto ( limit -- seq )
81 dup initialize-sieve 2 swap [a..b) [
82 dup is-prime? [ increment-counts ] [ drop ] if
85 : consecutive-under ( limit m -- n/f )
86 [ prime-tau-upto ] [ dup <repetition> ] bi* subseq-index ;
90 : euler047a ( -- answer )
91 200000 4 consecutive-under ;
93 ! [ euler047a ] 100 ave-time
94 ! 331 ms ave run time - 19.14 SD (100 trials)
96 ! TODO: I don't like that you have to specify the upper bound, maybe try making
97 ! this lazy so it could also short-circuit when it finds the answer?