Monday, March 14, 2011

Project Euler-Problem 16

Description

From Project Euler:

215 = 32,768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 21000?

Solution

This is another one of those problems that Ruby makes so easy by having a built-in arbitrary precision integer. Also, remember that back in problem 8 we created a method on Integer that will return an array with the digits of an integer. Putting these two elements together, we come to the very simple solution:

(2**1000).digits.reduce(:+)

The full source and specifications can be seen on github. Next time, how many letters would be needed to write all the numbers in words from 1 to 1000?

No comments: