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

7

17

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

If the number is a square number, it returns true and otherwise false. Negative numbers also return false.

Examples:

isSquare(-12) // => false
isSquare( 5) // => false
isSquare( 9) // => true
isSquare(25) // => true
isSquare(27) // => false

Right now, I am using this method: http://jsfiddle.net/marcusdei/ujtc82dq/5/

But, is there a shorter more cleaner way to get the job done?

Elasticize answered 18/6, 2015 at 15:5 Comment(2)
What exactly is wrong with the referenced method? Doesn't go much shorter than that... (and it's pretty clean too IMO)Sonora
yes, I just find this one even shorter, not sure about cleaner though: jsfiddle.net/marcusdei/ujtc82dq/7Elasticize
M
54

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

Mvd answered 18/6, 2015 at 15:8 Comment(3)
I don't think you need to check if the value is > 0. Also 0 is technically a square number. In your case it would evaluate to false.Shawntashawwal
@Shawntashawwal For 0 as perfect square, you're right. For negative numbers, one function call can be saved.Mvd
n >= 0 && ... - to include 0Asperse
T
9

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

Teletypesetter answered 17/4, 2018 at 14:55 Comment(0)
V
5

//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
};
Vientiane answered 9/5, 2020 at 15:29 Comment(1)
CodeSignal tests state that the 1st method is the fastest! (note: 0 is full square also)Carrefour
O
4

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));
Otoole answered 14/10, 2020 at 3:38 Comment(0)
L
3

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
Luck answered 31/3, 2020 at 0:43 Comment(0)
G
1

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.

Goodard answered 16/11, 2019 at 18:24 Comment(0)
K
0

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.

Katelynnkaterina answered 18/3, 2020 at 12:24 Comment(2)
Hi AnonymousContribute, isn't your answer the same as Stephane's answer: https://mcmap.net/q/685879/-what-39-s-the-best-way-in-javascript-to-test-if-a-given-parameter-is-a-square-number ?If so, please upvote this answer instead of adding your own :)Epileptic
There is at least one case where this fails: number = nullMccarthyism

© 2022 - 2024 — McMap. All rights reserved.