021.sml 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. (*
  2. Amicable numbers
  3. Problem 21
  4. Let d(n) be defined as the sum of proper divisors of n (numbers less
  5. than n which divide evenly into n). If d(a) = b and d(b) = a, where a
  6. ≠ b, then a and b are an amicable pair and each of a and b are called
  7. amicable numbers.
  8. For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20,
  9. 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284
  10. are 1, 2, 4, 71 and 142; so d(284) = 220.
  11. Evaluate the sum of all the amicable numbers under 10000.
  12. *)
  13. fun print_int_list nil = print ""
  14. | print_int_list (num::nums) =
  15. let
  16. val _ = print (String.concat [(Int.toString num), "\n"]);
  17. in
  18. print_int_list nums
  19. end;
  20. fun sum nil = 0
  21. | sum lst = foldl op+ 0 lst;
  22. fun is_divisor num factor =
  23. (num mod factor) = 0;
  24. fun divisors num =
  25. let
  26. fun iter 1 factors = 1 :: factors
  27. | iter 0 factors = nil
  28. | iter n factors =
  29. if is_divisor num n
  30. then iter (n - 1) (n :: factors)
  31. else iter (n - 1) factors;
  32. in
  33. iter (num div 2) nil
  34. end;
  35. fun sum_divisors num =
  36. sum (divisors num);
  37. fun is_amicable num =
  38. let
  39. val divisor_sum = sum_divisors num;
  40. in
  41. (num = (sum_divisors divisor_sum)
  42. andalso
  43. not (num = divisor_sum))
  44. end;
  45. fun calculate_sum_amicable_numbers limit =
  46. let
  47. fun iter 1 sum = iter 2 sum
  48. | iter num sum =
  49. (* cannot pattern-match with "limit" as name, because it
  50. would be interpreted as shadowing the outer limit
  51. binding. *)
  52. if num < limit
  53. then
  54. if is_amicable num then
  55. (* let only for printing something *)
  56. let
  57. val _ = print (String.concat ["amicable number:", Int.toString num, "\n"]);
  58. in
  59. iter (num + 1) (sum + num)
  60. end
  61. else
  62. iter (num + 1) sum
  63. else
  64. sum
  65. in
  66. iter 1 0
  67. end;
  68. calculate_sum_amicable_numbers 10000;