How can I check is a number is a Dudeney Number, using Ruby? -
how can check if number dudeney number, using ruby? taking examples or evidence, these results:
dudeney_number?(1) #=> true dudeney_number?(125) #=> false dudeney_number?(512) #=> true dudeney_number?(1728) #=> false dudeney_number?(5832) #=> true
from https://en.wikipedia.org/wiki/dudeney_number:
a dudeney number positive integer perfect cube such sum of decimal digits equal cube root of number.
here's implementation definition:
def dudeney_number?(n) digit_sum = n.to_s.chars.map(&:to_i).inject(:+) n == digit_sum ** 3 end 1.upto(20000).select { |n| dudeney_number? n } #=> [1, 512, 4913, 5832, 17576, 19683]
the method doesn't check if n
positive integer.
Comments
Post a Comment