admin管理员组文章数量:1401620
I want to find the sum of all digits of a large number, for example 9995.
I applied BigInt to get the power of large number and sum its digits together using the code below.
BigInt(Math.pow(99, 95)).toString().split("").reduce((a, b) => a * 1 + b * 1)
However, it returns 845
, but the correct answer should be 972
.
I have checked the integer output of the large number. In JavaScript it is:
3848960788934848488282452569509484590776195611314554049114673132510910096787679715604422673797115451807631980373077374162416714994207463122539142978709403811688831410945323915071533162168320
This is not the same as the correct answer (in C#):
3848960788934848611927795802824596789608451156087366034658627953530148126008534258032267383768627487094610968554286692697374726725853195657679460590239636893953692985541958490801973870359499
.
I am wondering what’s wrong in my code causing the differences.
I want to find the sum of all digits of a large number, for example 9995.
I applied BigInt to get the power of large number and sum its digits together using the code below.
BigInt(Math.pow(99, 95)).toString().split("").reduce((a, b) => a * 1 + b * 1)
However, it returns 845
, but the correct answer should be 972
.
I have checked the integer output of the large number. In JavaScript it is:
3848960788934848488282452569509484590776195611314554049114673132510910096787679715604422673797115451807631980373077374162416714994207463122539142978709403811688831410945323915071533162168320
This is not the same as the correct answer (in C#):
3848960788934848611927795802824596789608451156087366034658627953530148126008534258032267383768627487094610968554286692697374726725853195657679460590239636893953692985541958490801973870359499
.
I am wondering what’s wrong in my code causing the differences.
Share Improve this question edited Nov 30, 2022 at 9:05 Sebastian Simon 19.6k8 gold badges61 silver badges84 bronze badges asked Jun 21, 2019 at 3:27 SKLTFZSKLTFZ 9502 gold badges11 silver badges36 bronze badges2 Answers
Reset to default 7The expression Math.pow(99, 95)
, when it resolves, has already lost precision - casting it to a BigInt after the fact does not recover the lost precision.
Use BigInts from the beginning instead, and use **
instead of Math.pow
so that the exponentiation works:
console.log(
(99n ** 95n)
.toString()
.split('')
.reduce((a, b) => a + Number(b), 0)
);
BigInt(Math.pow(99,95))
This runs math pow on 2 floats, then converts it to bigint.
You want BigInt(99) ** BigInt(95)
instead
本文标签: javascriptWhy is BigInt(largeNumber) still not preciseStack Overflow
版权声明:本文标题:javascript - Why is BigInt(largeNumber) still not precise? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744295241a2599310.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论