Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript how to multiply BigInt ** 0.5?

Tags:

javascript

i am converting python code to js but cannot resolve this one x = int(num ** 0.5) (num is big integer)

how to calculate this in javascript BigInt ?

thanks i solved it

var num = BigInt("14564566644656456665555555555555555555555555545654645"); //example
num = BigInt(Math.round(parseInt(num.toString()) ** 0.5 )); // result is exact same as python tested more 
like image 400
Deran Toli Avatar asked Sep 10 '25 15:09

Deran Toli


1 Answers

You can do it with bignumber.js. You'll need to convert the BigInt to a BigNumber, compute the square root (sqrt), and then round it to an integer with toFixed:

function sqrt( x ) {
  return BigInt( BigNumber( x ).sqrt().toFixed(0) );
}

console.log( sqrt( 14564566644656456665555555555555555555555555545654645n ).toString() );
<script src="https://unpkg.com/[email protected]/bignumber.min.js"></script>

Your current solutions in JavaScript and Python are off by 1897074225, because you are converting to floating point math which doesn't have enough precision for the BigInt you are using. Is floating point math broken?

like image 147
Paul Avatar answered Sep 13 '25 05:09

Paul