Euler Problems 13 and 16

Posted Thu, Jan 1 2009 8:44 PM by amarsan
Awhile back I solved Euler problem 13, and then today I took a look at problem 16 and noticed that it's very similar. Problem 13 asks us to find the first 10 digits of the sum of 100 50-digit numbers. The first thing one notes immediately is that you can't store a 50 digit number with a long int in MATLAB; it needs to be stored as a string. So, provided that I've stored the specific 100 numbers that Project Euler wants me to add in a string array called bigNumbers, I can solve the problem with the following line of code:
sum(str2num(bigNumbers))
The str2num MATLAB built-in function converts a string to a numerical value. The sum function takes care of the rest. Problem 16 challenges us to sum the digits in the number 2^1000. Once again, one line of MATALB does the trick:
sum(str2num(num2str(2^1000)'))
In this case I convert the large number (2^1000) to a character array (using num2str), transpose the array so I can treat each digit individually, then convert back to a numerical value and compute the sum.