You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中仅用for循环找出范围内的完全平方数(禁Math.sqrt())

筛选0到max-1范围内的完全平方数

方法一:遍历判断法

你之前用Math.sqrt()得到平方根数组,应该是误把平方根值push进数组了。正确的逻辑是:遍历0到max-1的每个数,计算它的平方根,判断该平方根是否为整数,若是则将原数加入结果数组:

function getNumbersWithSquareRoots(max) {
  const arrNum = [];
  for(let i = 0; i < max; i++) {
    const sqrtVal = Math.sqrt(i);
    // 校验平方根是否为整数
    if(Number.isInteger(sqrtVal)) {
      arrNum.push(i);
    }
  }
  return arrNum;
}

方法二:直接生成法(更高效)

完全平方数本质是整数的平方,我们可以直接从0开始计算整数的平方值,直到平方值超过max-1为止,这种方式不用遍历所有数,效率更高:

function getNumbersWithSquareRoots(max) {
  const arrNum = [];
  for(let n = 0; ; n++) {
    const square = n * n;
    if(square >= max) {
      break;
    }
    arrNum.push(square);
  }
  return arrNum;
}

比如当max=200时,第二个方法会依次计算0²=0、1²=1……直到14²=196,当n=15时15²=225≥200,循环终止,返回的数组正好是[0, 1, 4, 9, 16,…, 196]。

内容的提问来源于stack exchange,提问作者OldsoulPhil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 19:26:14