是JavaScript中两个完美平方的和

完美平方数:

如果数学上的自然数可以通过将任何其他自然数乘以该正数而获得,则称为完美平方。

例如,9、16、81、289都是完美的正方形。

我们需要编写一个以自然数(例如num)作为唯一参数的JavaScript函数。该函数应确定是否存在两个这样的数字m和n使得-

(m * m) + (n * n) = num

如果存在此类数字,则我们的函数应返回true,否则返回false。

例如-

如果输入号码是-

const num = 389;

那么输出应该是-

const output = true;

因为389 =(17 * 17)+(10 * 10)

示例

为此的代码将是-

const num = 389;
const canSumSquares = (num = 2) => {
   let left = 0, right = Math.floor(Math.sqrt(num));
   while(left <= right){
      if (left * left + right * right === num) {
         return true;
      } else if (left * left + right * right < num) {
         left++;
         } else {
            right--;
      };
   };
   return false;
};
console.log(canSumSquares(num));
输出结果

控制台中的输出将是-

true