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

조회 수: 3 (최근 30일)
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));

채택된 답변

John D'Errico
John D'Errico 2019년 1월 26일
편집: John D'Errico 2019년 1월 26일
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
Eqan Ahmad
Eqan Ahmad 2019년 1월 26일
편집: Eqan Ahmad 2019년 1월 26일
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 2019년 1월 27일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Conversion Between Symbolic and Numeric에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by