1 ! Copyright (c) 2008 Aaron Schaefer.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel math math.functions math.ranges project-euler.common sequences ;
6 ! http://projecteuler.net/index.php?section=problems&id=44
11 ! Pentagonal numbers are generated by the formula, Pn=n(3nā1)/2. The first ten
12 ! pentagonal numbers are:
14 ! 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
16 ! It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference,
17 ! 70 ā 22 = 48, is not pentagonal.
19 ! Find the pair of pentagonal numbers, Pj and Pk, for which their sum and
20 ! difference is pentagonal and D = |Pk ā Pj| is minimised; what is the value of D?
26 ! Brute force using a cartesian product and an arbitrarily chosen limit.
30 : nth-pentagonal ( n -- seq )
33 : sum-and-diff? ( m n -- ? )
34 [ + ] [ - ] 2bi [ pentagonal? ] bi@ and ;
38 : euler044 ( -- answer )
39 2500 [1,b] [ nth-pentagonal ] map dup cartesian-product
40 [ first2 sum-and-diff? ] filter [ first2 - abs ] map infimum ;
42 ! [ euler044 ] 10 ave-time
43 ! 4996 ms ave run time - 87.46 SD (10 trials)
45 ! TODO: this solution is ugly and not very efficient...find a better algorithm