021 Amicable numbers -- v2.sf 618 B

123456789101112131415161718192021222324252627282930313233
  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.393s
  9. func proper_sigma(n) {
  10. n.sigma - n
  11. }
  12. var total = 0
  13. for a in (2 ..^ 10000) {
  14. var b = proper_sigma(a)
  15. next if (b <= a)
  16. var c = proper_sigma(b)
  17. if (c == a) {
  18. say "#{a} #{b}"
  19. total += a+b
  20. }
  21. }
  22. say total