JavaScript 中测试给定参数是否为平方数的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30919111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:56:38  来源:igfitidea点击:

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

javascriptnumbersperfect-square

提问by Mike. D

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

在此处阅读平方数:https: //en.wikipedia.org/?title=Square_number

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

如果数字是平方数,则返回true,否则返回false。负数也返回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/

现在,我正在使用这种方法:http: //jsfiddle.net/marcusdei/ujtc82dq/5/

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

但是,是否有更短更清洁的方法来完成工作?

回答by Tushar

Try this:

尝试这个:

var isSquare = function (n) {
    return n > 0 && Math.sqrt(n) % 1 === 0;
};
  1. Check if number is positive
  2. Check if sqrtis complete number i.e. integer
  1. 检查数字是否为正
  2. 检查数字是否sqrt完整,即integer

Demo

演示

回答by Stephane Moreau

I would definitely go for:

我肯定会去:

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

PS: 0is a square number for those who wonder

PS:0对于那些想知道的人来说是一个平方数

Demo

演示

回答by ASHISH RANJAN

//1st 
var isPerfectSquare = function(num) {
   return Math.sqrt(num) % 1 === 0;
}

//2nd: loop through all the number from 1 to num 
var isPerfectSquare = function(num) {
    
    for(let i=1; i <= num ; i++){
        let d = i * i;
        if(d === num){
            return true
        }
    }
}

// Optimize solution: Binary Search 
var isPerfectSquare = function(num) {

    if(num ==1)return true
    let left = 2;
    let right = Math.floor(num/2);
    while(left <= right){
        let middle = Math.floor((left + right)/2)
        let sqr = middle * middle;
        if(sqr == num){
            return true
        }else{
            if(sqr > num){
              right = middle -1
            }else{
                left = middle + 1
            }
        }  
    }
    
    return false
};

回答by Jeff Lowery

It's a bit trickier if you're using the new BigInt in JavaScript:

如果您在 JavaScript 中使用新的 BigInt,这会有点棘手:

// 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:

我发现(到目前为止)确定 n 是否为正方形的最好和最快的方法是:

function isSquare(n) {
   return n%sqrt(n) === 0n
}

But there's gotta be a faster way for BigInt operations.

但是必须有一种更快的方式来进行 BigInt 操作。

回答by AnonymousContribute

Isn't this (Math.sqrt(number) % 1 === 0) basically enough? it just checks if the sqrt of the number is a whole number, if so, then it's a perfect square.

这不是 (Math.sqrt(number) % 1 === 0) 基本上够了吗?它只是检查数字的 sqrt 是否是整数,如果是,则它是一个完美的正方形。

Obviously, depending on what you want to do with that information, it may require extra code.

显然,根据您想对这些信息做什么,它可能需要额外的代码。

回答by A.McLoof

I think that this one is a shorter and a cleaner option:

我认为这是一个更短更干净的选择:

  var isSquare = function(n) {

  return Number.isInteger(Math.sqrt(n));
};

isSquare(25); //true

for even shorter and cleaner than that you could use:

比你可以使用的更短更干净:

var isSquare = n => Number.isInteger(Math.sqrt(n));

isSquare(25);//true