Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 964
Marco V Avatar asked Jun 18 '15 15:06

Marco V


People also ask

How do you quickly check if a number is a perfect square?

To check the perfectness of your square, you can simply calculate the square root of a given number. If the square root is an integer, your number is the perfect square. Let's calculate the squares of the following numbers: 49 and 53 . √49 = 7 - 7 is an integer → number 49 is a perfect square.


1 Answers

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

like image 195
Tushar Avatar answered Sep 21 '22 08:09

Tushar