ADVERTISEMENT

What's the best way in JavaScript to test if a given parameter is a square number?

Try this:

var isSquare = function (n) {
    return n > 0 && Math.sqrt(n) % 1 === 0;
};
  1. Check if number is positive
  2. Check if sqrt is complete number i.e. integer

Demo


I would definitely go for:

var isSquare = function (n) {
    return Math.sqrt(n) % 1 === 0;
};

PS: 0 is a square number for those who wonder

Demo


//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
};