在 JavaScript 中查找给定范围内的阿姆斯特朗数

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/26 5:32:17

如果以下等式适用于某个数字,则该数字称为阿姆斯特朗数: xy...z =xx +yy+...+zz,其中 n 表示数字中的位数。

例如:

153 是阿姆斯特朗数,因为 −

11 +55 +33 = 1 + 125 + 27 =153

我们需要编写一个 JavaScript 函数,该函数接受两个数字和一个范围,并返回它们之间的所有阿姆斯特朗数(如果它们是阿姆斯特朗数,则包括它们)

示例

其代码为 −

const isArmstrong = number => {
   let num = number;
   const len = String(num).split("").length;
   let res = 0;
   while(num){
      const last = num % 10;
      res += Math.pow(last, len);
      num = Math.floor(num / 10);
   };
   return res === number;
};
const armstrongBetween = (lower, upper) => {
   const res = [];
   for(let i = lower; i <= upper; i++){
      if(isArmstrong(i)){
         res.push(i);
      };
   };
   return res;
};
console.log(armstrongBetween(1, 400));

输出

控制台中的输出 −

[
   1, 2, 3, 4, 5,
   6, 7, 8, 9, 153,
   370, 371
]

相关文章


有用资源