]> gitweb.factorcode.org Git - factor.git/blob - extra/project-euler/044/044.factor
Delete empty unit tests files, remove 1- and 1+, reorder IN: lines in a lot of places...
[factor.git] / extra / project-euler / 044 / 044.factor
1 ! Copyright (c) 2008 Aaron Schaefer.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel math math.functions math.ranges math.order
4 project-euler.common sequences ;
5 IN: project-euler.044
6
7 ! http://projecteuler.net/index.php?section=problems&id=44
8
9 ! DESCRIPTION
10 ! -----------
11
12 ! Pentagonal numbers are generated by the formula, Pn=n(3nāˆ’1)/2. The first ten
13 ! pentagonal numbers are:
14
15 !     1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
16
17 ! It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference,
18 ! 70 āˆ’ 22 = 48, is not pentagonal.
19
20 ! Find the pair of pentagonal numbers, Pj and Pk, for which their sum and
21 ! difference is pentagonal and D = |Pk āˆ’ Pj| is minimised; what is the value of D?
22
23
24 ! SOLUTION
25 ! --------
26
27 ! Brute force using a cartesian product and an arbitrarily chosen limit.
28
29 <PRIVATE
30
31 : nth-pentagonal ( n -- seq )
32     dup 3 * 1 - * 2 / ;
33
34 : sum-and-diff? ( m n -- ? )
35     [ + ] [ - ] 2bi [ pentagonal? ] bi@ and ;
36
37 PRIVATE>
38
39 : euler044 ( -- answer )
40     2500 [1,b] [ nth-pentagonal ] map dup cartesian-product
41     [ first2 sum-and-diff? ] filter [ first2 - abs ] [ min ] map-reduce ;
42
43 ! [ euler044 ] 10 ave-time
44 ! 4996 ms ave run time - 87.46 SD (10 trials)
45
46 ! TODO: this solution is ugly and not very efficient...find a better algorithm
47
48 SOLUTION: euler044