1 ! Copyright (c) 2008 Aaron Schaefer.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: arrays kernel math math.order math.primes
4 project-euler.common sequences ;
7 ! http://projecteuler.net/index.php?section=problems&id=50
12 ! The prime 41, can be written as the sum of six consecutive primes:
14 ! 41 = 2 + 3 + 5 + 7 + 11 + 13
16 ! This is the longest sum of consecutive primes that adds to a prime below
19 ! The longest sum of consecutive primes below one-thousand that adds to a
20 ! prime, contains 21 terms, and is equal to 953.
22 ! Which prime, below one-million, can be written as the sum of the most
29 ! 1) Create an sequence of all primes under 1000000.
30 ! 2) Start summing elements in the sequence until the next number would put you
32 ! 3) Check if that sum is prime, if not, subtract the last number added.
33 ! 4) Repeat step 3 until you get a prime number, and store it along with the
34 ! how many consecutive numbers from the original sequence it took to get there.
35 ! 5) Drop the first number from the sequence of primes, and do steps 2-4 again
36 ! 6) Compare the longest chain from the first run with the second run, and store
37 ! the longer of the two.
38 ! 7) If the sequence of primes is still longer than the longest chain, then
39 ! repeat steps 5-7...otherwise, you've found the longest sum of consecutive
44 :: sum-upto ( seq limit -- length sum )
45 0 seq [ + dup limit > ] find
46 [ swapd - ] [ drop seq length swap ] if* ;
48 : pop-until-prime ( seq sum -- seq prime )
50 [ unclip-last-slice ] dip swap -
51 dup prime? [ pop-until-prime ] unless
56 ! a pair is { length of chain, prime the chain sums to }
58 : longest-prime ( seq limit -- pair )
59 dupd sum-upto dup prime? [
62 [ head-slice ] dip pop-until-prime
66 : continue? ( pair seq -- ? )
67 [ first ] [ length 1 - ] bi* < ;
69 : (find-longest) ( best seq limit -- best )
70 [ longest-prime max ] 2keep 2over continue? [
71 [ rest-slice ] dip (find-longest)
74 : find-longest ( seq limit -- best )
75 { 1 2 } -rot (find-longest) ;
77 : solve ( n -- answer )
78 [ primes-upto ] keep find-longest second ;
82 : euler050 ( -- answer )
85 ! [ euler050 ] 100 ave-time
86 ! 291 ms run / 20.6 ms GC ave time - 100 trials