Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var BigInt = require('big-integer');
- function sqrt(c) {
- if (c.isZero()) {
- return c;
- }
- if (c.lesser(4)) {
- return BigInt(1);
- }
- var n, p;
- var high = c.shiftRight(1);
- var low = BigInt.zero;
- while (high.greater(low.add(1))) {
- n = high.add(low).shiftRight(1);
- p = n.square();
- if (c.lesser(p)) {
- high = n;
- } else if (c.greater(p)) {
- low = n.equals(1) ? n.add(1) : n;
- } else {
- break;
- }
- }
- if (c.equals(p)) {
- return n;
- } else if (c.equals(high.square())) {
- return high;
- }
- return low;
- }
Advertisement
Add Comment
Please, Sign In to add comment