MATLAB: Adding all the digits in a large number gives me an incorrect result

charconverteulerhelpMATLABnum2strstr2num

So I am trying to add all the individual in 100! but the output is 683. Weirdly, this works with smaller numbers.
factnum = sprintf("%.f",factorial(5));
charfact = convertStringsToChars(factnum);
i = 1;
for i = 1:length(charfact)
x(i) = str2num(charfact(i));
end
disp(sum(x));

Best Answer

How large is 100! ?
factorial(100)
ans =
9.33262154439441e+157
So a number with what, 158 digits? How many digits does a double precision number have in MATLAB? (Roughly 16.)
So you are only 142 digits short. Of course it works for factorial(5), which is what, 120? A 3 digit number? No problem.
This is clearly homework, so you are going to need to think of something more creative, since I won't do your homework for you. You might expand those multiplications essentially long hand. Or you might use syms. Hey, at least you won't have to add up those 24 trailing zeros. In case you are wondering, either of the approaches I mentioned are quite easy to implement. Or, I suppose you could be really lazy and use my VPI toolbox. This should work:
sum(digits(factorial(vpi(100))))
Or, you could spend some time and learn to use the java.math.BigInteger tools.
(Actually, 683 is not that terribly far off. Lets see, 158 digits. Assume a uniform distribution, so each digit contributes 4.5 to the average. 158*4.5=711. But there are 24 known trailing zeros, which are not contributing to that average. So 600-700 should be in the right ballpark for the sum.)