BigInt issue of javascript

Viewed 1232

I want to find a sum of all integers of a large number for example

power(99,95)

I applied bigInt to get the power of large number and sum it together by below code.

BigInt(Math.pow(99,95)).toString().split('').reduce(function(a,b){return 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 is

3848960788934848488282452569509484590776195611314554049114673132510910096787679715604422673797115451807631980373077374162416714994207463122539142978709403811688831410945323915071533162168320

Which is not the same as the correct answer (in C#)

3848960788934848611927795802824596789608451156087366034658627953530148126008534258032267383768627487094610968554286692697374726725853195657679460590239636893953692985541958490801973870359499

I am wondering whats wrong in my code causing the differences?

2 Answers

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

Related