范围之间的阿姆斯特朗数 - JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/5 0:44:17

如果以下等式对该数成立,则该数称为阿姆斯特朗数 −

xy..z = x^n + y^n+.....+ z^n

其中,n 表示数字中的位数

例如 − 370 是阿姆斯特朗数,因为 −

3^3 + 7^3 + 0^3 = 27 + 343 + 0 = 370

我们需要编写一个 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
]

相关文章


有用资源