Adding all the digits in a large number gives me an incorrect result
    3 views (last 30 days)
  
       Show older comments
    
    Eqan Ahmad
 on 26 Jan 2019
  
    
    
    
    
    Commented: John D'Errico
      
      
 on 27 Jan 2019
            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));
0 Comments
Accepted Answer
  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
  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.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
