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

3 views (last 30 days)
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));

Accepted Answer

John D'Errico
John D'Errico on 26 Jan 2019
Edited: John D'Errico on 26 Jan 2019
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.)
  5 Comments
Eqan Ahmad
Eqan Ahmad on 26 Jan 2019
Edited: Eqan Ahmad on 26 Jan 2019
I am trying hard to implement it! Just need some time to understand methods().
EDIT:
I GOT IT
sum(char(factorial(sym(100)))-'0')
I was so confused with method(), thank you so much John. I will be using this a lot from now on. Much more efficient than what I started off with.
John D'Errico
John D'Errico on 27 Jan 2019
Well done. I was hoping you would get it yourself. The trick here was to recognize that once you have the symbolic form, you can convert it to a string of characters. Once you have that, subtracting '0' is the simple way in MATLAB to convert achar string to a vector of numbers. And then just sum. So a few tricks you wanted to learn. But having done so, you know them, and now they are yours for the next problem to be solved.

Sign in to comment.

More Answers (0)

Products


Release

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!