-! Copyright (c) 2007 Aaron Schaefer.
+! Copyright (c) 2008 Aaron Schaefer.
! See http://factorcode.org/license.txt for BSD license.
-USING: kernel math math.primes project-euler.common sequences ;
+USING: kernel math math.primes math.ranges project-euler.common sequences ;
IN: project-euler.027
! http://projecteuler.net/index.php?section=problems&id=27
! b must be prime since n = 0 must return a prime
! a + b + 1 must be prime since n = 1 must return a prime
-! a < b
+! 1 - a + b must be prime as well, hence >= 2. Therefore:
+! 1 - a + b >= 2
+! b - a >= 1
+! a < b
<PRIVATE
: source-027 ( -- seq )
- 1000 [ prime? ] subset [ dup [ neg ] map append ] keep
- cartesian-product [ first2 < ] subset ;
+ 1000 [0,b) [ prime? ] filter [ dup [ neg ] map append ] keep
+ cartesian-product [ first2 < ] filter ;
: quadratic ( b a n -- m )
dup sq -rot * + + ;
: (consecutive-primes) ( b a n -- m )
- 3dup quadratic prime? [ 1+ (consecutive-primes) ] [ 2nip ] if ;
+ 3dup quadratic prime? [ 1 + (consecutive-primes) ] [ 2nip ] if ;
: consecutive-primes ( a b -- m )
swap 0 (consecutive-primes) ;
: max-consecutive ( seq -- elt n )
dup [ first2 consecutive-primes ] map dup supremum
- over index [ swap nth ] curry 2apply ;
+ over index [ swap nth ] curry bi@ ;
PRIVATE>
source-027 max-consecutive drop product ;
! [ euler027 ] 100 ave-time
-! 687 ms run / 23 ms GC ave time - 100 trials
+! 111 ms ave run time - 6.07 SD (100 trials)
! TODO: generalize max-consecutive/max-product (from #26) into a new word
-MAIN: euler027
+SOLUTION: euler027