armstrong_numbers.sf 956 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #!/usr/bin/ruby
  2. # Generate Armstrong numbers.
  3. # Armstrong (or pluperfect, or Plus Perfect, or narcissistic) numbers: m-digit positive numbers equal to sum of the m-th powers of their digits.
  4. # https://oeis.org/A005188
  5. # See also:
  6. # https://rosettacode.org/wiki/Own_digits_power_sum
  7. func armstrong_numbers(n, base=10) {
  8. var D = @(^base)
  9. var P = D.map {|d| d**n }
  10. var list = []
  11. D.combinations_with_repetition(n, {|*c|
  12. var v = c.sum {|d| P[d] }
  13. if (v.digits(base).sort == c) {
  14. list.push(v)
  15. }
  16. })
  17. list.sort
  18. }
  19. for n in (3..6) {
  20. say ("For n = #{'%2d' % n}: ", armstrong_numbers(n))
  21. }
  22. __END__
  23. For n = 3: [153, 370, 371, 407]
  24. For n = 4: [1634, 8208, 9474]
  25. For n = 5: [54748, 92727, 93084]
  26. For n = 6: [548834]
  27. For n = 7: [1741725, 4210818, 9800817, 9926315]
  28. For n = 8: [24678050, 24678051, 88593477]
  29. For n = 9: [146511208, 472335975, 534494836, 912985153]
  30. For n = 10: [4679307774]