Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  14] [ 6]  / answers: 1 / hits: 53910  / 9 Years ago, thu, june 18, 2015, 12:00:00

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?


More From » numbers

 Answers
5

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


[#66150] Wednesday, June 17, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trayvon

Total Points: 35
Total Questions: 117
Total Answers: 88

Location: Guernsey
Member since Tue, Jul 6, 2021
3 Years ago
;