]> gitweb.factorcode.org Git - factor.git/blob - extra/project-euler/021/021.factor
ef0d4191dea9ccb31ffacb332300cef36c400d0b
[factor.git] / extra / project-euler / 021 / 021.factor
1 ! Copyright (c) 2007 Aaron Schaefer.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: combinators.short-circuit kernel math math.functions
4     math.ranges namespaces project-euler.common sequences ;
5 IN: project-euler.021
6
7 ! http://projecteuler.net/index.php?section=problems&id=21
8
9 ! DESCRIPTION
10 ! -----------
11
12 ! Let d(n) be defined as the sum of proper divisors of n (numbers less than n
13 ! which divide evenly into n).
14
15 ! If d(a) = b and d(b) = a, where a != b, then a and b are an amicable pair and
16 ! each of a and b are called amicable numbers.
17
18 ! For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44,
19 ! 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4,
20 ! 71 and 142; so d(284) = 220.
21
22 ! Evaluate the sum of all the amicable numbers under 10000.
23
24
25 ! SOLUTION
26 ! --------
27
28 : amicable? ( n -- ? )
29     dup sum-proper-divisors
30     { [ = not ] [ sum-proper-divisors = ] } 2&& ;
31
32 : euler021 ( -- answer )
33     10,000 [1..b] [ dup amicable? [ drop 0 ] unless ] map-sum ;
34
35 ! [ euler021 ] 100 ave-time
36 ! 335 ms ave run time - 18.63 SD (100 trials)
37
38 SOLUTION: euler021