What is the best way in JavaScript to check if a given parameter is a square number?

I created a function that will check if a given parameter is a square number.

Read the square numbers here: https://en.wikipedia.org/?title=Square_number

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

Examples:

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

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

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

+4
source share
2 answers

Try the following:

var isSquare = function (n) {
    return n > 0 && Math.sqrt(n) % 1 === 0;
};
  • Check that the number is positive
  • Check if the sqrtfull number is ieinteger

Demo

+21

:

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

PS. 0 - ,

0

All Articles