021 Amicable numbers.sf 690 B

12345678910111213141516171819202122232425262728293031323334353637
  1. #!/usr/bin/ruby
  2. # Daniel "Trizen" Șuteu
  3. # https://github.com/trizen
  4. # For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284.
  5. # The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
  6. # Evaluate the sum of all the amicable numbers under 10000.
  7. # https://projecteuler.net/problem=21
  8. # Runtime: 0.417s
  9. var sum = 0
  10. var mem = Hash()
  11. for i in (2 ..^ 10000) {
  12. var d = i.sigma-i
  13. if (mem.exists(d)) {
  14. var n = mem{d}
  15. if (n.sigma-n == d) {
  16. sum += d+n
  17. say "#{d} #{n}"
  18. }
  19. mem.delete(d)
  20. }
  21. elsif (i != d) {
  22. mem{i} = d
  23. }
  24. }
  25. say "Sum: #{sum}"