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
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With