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.
I went that route:
var isSquare = (n) => n === 0 ? true : n > 0 && Math.sqrt(n) % 1 === 0;
console.log(isSquare(25));
console.log(isSquare(10));
console.log(isSquare(16));
Isn't this (Math.sqrt(number) % 1 === 0) basically enough? it just checks if the sqrt of the number is a whole number, if so, then it's a perfect square.
Obviously, depending on what you want to do with that information, it may require extra code.
I think that this one is a shorter and a cleaner option:
var isSquare = function(n) {
return Number.isInteger(Math.sqrt(n));
};
isSquare(25); //true
for even shorter and cleaner than that you could use:
var isSquare = n => Number.isInteger(Math.sqrt(n));
isSquare(25);//true
//1st
var isPerfectSquare = function(num) {
return Math.sqrt(num) % 1 === 0;
}
//2nd: loop through all the number from 1 to num
var isPerfectSquare = function(num) {
for(let i=1; i <= num ; i++){
let d = i * i;
if(d === num){
return true
}
}
}
// Optimize solution: Binary Search
var isPerfectSquare = function(num) {
if(num ==1)return true
let left = 2;
let right = Math.floor(num/2);
while(left <= right){
let middle = Math.floor((left + right)/2)
let sqr = middle * middle;
if(sqr == num){
return true
}else{
if(sqr > num){
right = middle -1
}else{
left = middle + 1
}
}
}
return false
};
Try this:
var isSquare = function (n) {
return n > 0 && Math.sqrt(n) % 1 === 0;
};
sqrt
is complete number i.e. integer
Demo