function Sqrt( // Returns the square root of n, with decimal digits nDig n //number to compute square root , nDig //number of decimal digits in result , algo //Heron - for Babylonian method, or Newton for Newton Iteration method ) { if (n < 0n) { throw 'square root of negative numbers is not supported' } if (n < 2n) { return n; } n = BigInt(n) * (10n ** BigInt(nDig*2)); //square have length nDig*2 var x = (algo=='Heron') ? n : 1n, y = 1n; while (true) { if(algo === 'Heron'){ if(x>y){ x = (x + y) / 2n; y = n / x; } else{ break; } } else if(algo === 'Newton'){ y = ((n / x) + x) >> 1n; if (x === y || x === (y - 1n)) { break; } x = y; } } return x; //return BigInt } var result; result = '1.'+Sqrt(2, 1000, 'Heron' ).toString(10).slice(1); // -> 1000 decimal points of sqrt(2), using Babylonian method console.log(result); result = '1.'+Sqrt(2, 1000, 'Newton' ).toString(10).slice(1); // -> 1000 decimal points of sqrt(2), using Newton Iteration method console.log(result);