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

后端 未结 7 2610
忘了有多久
忘了有多久 2021-02-19 06:19

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

<
7条回答
  •  孤街浪徒
    2021-02-19 07:00

    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.

提交回复
热议问题