Problem 30

Statement
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:

1634 = 1⁴ + 6⁴ + 3⁴ + 4⁴
8208 = 8⁴ + 2⁴ + 0⁴ + 8⁴
9474 = 9⁴ + 4⁴ + 7⁴ + 4⁴

As 1 = 1⁴ is not a sum it is not included.

The sum of these numbers is 1634 + 8208 + 9474 = 19316.

Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.

Solution

class Fixnum
  def each_digits
    n = self
    while n>0
      yield n%10
      n /= 10
    end
  end
end

class PowerNumbers

  # The maximum used here is when the sum
  # of the powers of the n digits of a number
  # consisting of only 9 is smaller then this
  # number. We then know then all greater number
  # will be less.
  def initialize(power)
    @power = power
    @list = []
    max = 9
    digit = 1
    until digit*9**@power < max
      digit += 1
      max = max*10+9
    end
    (10..max).each do |i|
      sum = 0
      i.each_digits{|j| sum += j**@power}
      @list << i if i==sum
    end
  end
  def sum
    sum = 0
    @list.each {|i| sum += i}
    return sum
  end
end

spn = PowerNumbers.new(5)

puts spn.sum
No tags for this post.

SPEAK / ADD YOUR COMMENT
Comments are moderated.

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>