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 badges
Add a ment  | 

2 Answers 2

Reset to default 7

The 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