I created a function that will test to see if a given parameter is a square number.
Read about square numbers here: https://en.wikipedia.org/?title=Square_number
<
It's a bit trickier if you're using the new BigInt in JavaScript:
// integer square root function (stolen from the interwebs)
function sqrt(n) {
let a = 1n;
let b = (n >> 5n) + 8n;
while (b >= a) {
let mid = (a + b) >> 1n;
if (mid * mid > n) {
b = mid -= 1n;
} else {
a = mid += 1n;
}
}
return a -= 1n;
}
sqrt(25n) === 5n
sqrt(26n) === 5n
...
sqrt(35n) === 5n
The best and fastest way I've found (so far) to determine if n is a square is:
function isSquare(n) {
return n%sqrt(n) === 0n
}
But there's gotta be a faster way for BigInt operations.