]> gitweb.factorcode.org Git - factor.git/blob - extra/project-euler/050/050.factor
factor: trim using lists
[factor.git] / extra / project-euler / 050 / 050.factor
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 ;
5 IN: project-euler.050
6
7 ! http://projecteuler.net/index.php?section=problems&id=50
8
9 ! DESCRIPTION
10 ! -----------
11
12 ! The prime 41, can be written as the sum of six consecutive primes:
13
14 !     41 = 2 + 3 + 5 + 7 + 11 + 13
15
16 ! This is the longest sum of consecutive primes that adds to a prime below
17 ! one-hundred.
18
19 ! The longest sum of consecutive primes below one-thousand that adds to a
20 ! prime, contains 21 terms, and is equal to 953.
21
22 ! Which prime, below one-million, can be written as the sum of the most
23 ! consecutive primes?
24
25
26 ! SOLUTION
27 ! --------
28
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
31 !    over 1000000.
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
40 !    primes!
41
42 <PRIVATE
43
44 :: sum-upto ( seq limit -- length sum )
45     0 seq [ + dup limit > ] find
46     [ swapd - ] [ drop seq length swap ] if* ;
47
48 : pop-until-prime ( seq sum -- seq prime )
49     over length 0 > [
50         [ unclip-last-slice ] dip swap -
51         dup prime? [ pop-until-prime ] unless
52     ] [
53         2drop { } 0
54     ] if ;
55
56 ! a pair is { length of chain, prime the chain sums to }
57
58 : longest-prime ( seq limit -- pair )
59     dupd sum-upto dup prime? [
60         2array nip
61     ] [
62         [ head-slice ] dip pop-until-prime
63         [ length ] dip 2array
64     ] if ;
65
66 : continue? ( pair seq -- ? )
67     [ first ] [ length 1 - ] bi* < ;
68
69 : (find-longest) ( best seq limit -- best )
70     [ longest-prime max ] 2keep 2over continue? [
71         [ rest-slice ] dip (find-longest)
72     ] [ 2drop ] if ;
73
74 : find-longest ( seq limit -- best )
75     { 1 2 } -rot (find-longest) ;
76
77 : solve ( n -- answer )
78     [ primes-upto ] keep find-longest second ;
79
80 PRIVATE>
81
82 : euler050 ( -- answer )
83     1000000 solve ;
84
85 ! [ euler050 ] 100 ave-time
86 ! 291 ms run / 20.6 ms GC ave time - 100 trials
87
88 SOLUTION: euler050