2

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 
Deran Toli
  • 47
  • 1
  • 7
  • what is `**`? Is this in JS or python? You should add [minimal reproducible code](https://stackoverflow.com/help/minimal-reproducible-example). – DecPK Jul 25 '21 at 00:12
  • 1
    Unfortunately, I do not believe this is possible. See [TypeError: Cannot mix BigInt and other types, use explicit conversions](https://stackoverflow.com/questions/63591552/typeerror-cannot-mix-bigint-and-other-types-use-explicit-conversions) and [Why BigInt demand explicit conversion from Number?](https://stackoverflow.com/questions/57996921/why-bigint-demand-explicit-conversion-from-number). At a glance, it _appears_ that since `BigInt` is limited to _integers_ you can't do operations that would result in non-integer numbers, but I'm just scanning. – Alexander Nied Jul 25 '21 at 00:18
  • 3
    @decpk `**` has been a JavaScript operator for 5 years – Paul Jul 25 '21 at 00:19
  • am i stuck here? – Deran Toli Jul 25 '21 at 00:21
  • npm bigint-isqrt – Paul Jul 25 '21 at 00:22
  • @Paul I'm aware that it is a part of JS for a long time but It was not clear whether OP is talking about `**` in python or in JS – DecPK Jul 25 '21 at 00:22
  • Does this answer your question? [BigDecimal in JavaScript](https://stackoverflow.com/questions/16742578/bigdecimal-in-javascript) – TheRakeshPurohit Jul 25 '21 at 00:47
  • 1
    If you want to take the square root of a BigInt value, you'll have to write (or find) a BigInt oriented way of doing that. If the number is not a perfect square, you clearly cannot get an accurate BigInt result. – Pointy Jul 25 '21 at 00:55
  • it seems we manually have to do long division to find the square root – The Bomb Squad Jul 25 '21 at 01:31

1 Answers1

0

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/bignumber.js@9.0.1/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?

Paul
  • 139,544
  • 27
  • 275
  • 264