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

6 ビュー (過去 30 日間)
Eqan Ahmad
Eqan Ahmad 2019 年 1 月 26 日
コメント済み: John D'Errico 2019 年 1 月 27 日
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 Center および File ExchangeConversion 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