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

喜欢而已 提交于 2019-12-05 19:53:04

问题


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;
};
  1. Check if number is positive
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!