/extra/project-euler/021/021.factor

http://github.com/abeaumont/factor · Factor · 38 lines · 9 code · 12 blank · 17 comment · 5 complexity · e4d9f35264a6ca68752bce9cdf3c7a7f MD5 · raw file

  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. ! http://projecteuler.net/index.php?section=problems&id=21
  7. ! DESCRIPTION
  8. ! -----------
  9. ! Let d(n) be defined as the sum of proper divisors of n (numbers less than n
  10. ! which divide evenly into n).
  11. ! If d(a) = b and d(b) = a, where a != b, then a and b are an amicable pair and
  12. ! each of a and b are called amicable numbers.
  13. ! For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44,
  14. ! 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4,
  15. ! 71 and 142; so d(284) = 220.
  16. ! Evaluate the sum of all the amicable numbers under 10000.
  17. ! SOLUTION
  18. ! --------
  19. : amicable? ( n -- ? )
  20. dup sum-proper-divisors
  21. { [ = not ] [ sum-proper-divisors = ] } 2&& ;
  22. : euler021 ( -- answer )
  23. 10000 [1,b] [ dup amicable? [ drop 0 ] unless ] map-sum ;
  24. ! [ euler021 ] 100 ave-time
  25. ! 335 ms ave run time - 18.63 SD (100 trials)
  26. SOLUTION: euler021