I really enjoy doing programming problems every now and then. Euler Problems range in difficulty and they are all math related. They are a great exercise for someone who knows math/logic and is trying to dabble with a new programming language. I’ve completed Euler problems 1-15 in C# and was working on tackling problem 16 today. For those too lazy to click the link, the problem is rather simple:
215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 21000?
So the main problem with doing this in C# is that 21000 is a pretty big number and there aren’t any simple data types in C# that can hold a number that large. So the next place I went was Python, where you don’t have to worry about overflow – it just takes care of things for you auto-magically.
The algorithm is pretty straightforward:
- Calculate/store 21000
- Convert it to a string
- Print it, just to see how big it is
- Instantiate a new variable for the sum of digits
- Loop over each character in the string
- Add the converted-to-int character to the rolling sum
- Print the sum for checking
bigNumber = 2 ** 1000
str_bigNumber = str(bigNumber)
digitSum = 0
for dig in str_bigNumber:
digitSum += int(dig)
Dang, Python is fast! You can even use an online interpreter (I didn’t feel like downloading it).