问题
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?
回答1:
Try this:
var isSquare = function (n) {
return n > 0 && Math.sqrt(n) % 1 === 0;
};
- Check if number is positive
- Check if
sqrt
is complete number i.e.integer
Demo
回答2:
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
回答3:
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.
来源:https://stackoverflow.com/questions/30919111/whats-the-best-way-in-javascript-to-test-if-a-given-parameter-is-a-square-numbe