JavaScript范围内的阿姆斯壮数字
阿姆斯壮数字:如果满足以下条件,则一个正整数称为阿姆斯壮数字(n阶):
abcd... = a^n + b^n + c^n + d^n + ...
我们需要编写一个JavaScript函数,该函数接受一个正好两个数字的数组,这些数字指定一个范围。
该函数应返回该范围内所有阿姆斯壮数字的数组(如果它们是阿姆斯壮,则包括开始和结束数字)。
我们将首先单独编写一个函数以检测Armstrong数,然后遍历范围以将所需的数填充到数组中。
示例
以下是代码-
const range = [11, 1111];
const isArmstrong = (num) => {
const numberOfDigits = ('' + num).length;
let sum = 0;
let temp = num;
while (temp > 0) {
let remainder = temp % 10;
sum += remainder ** numberOfDigits;
temp = parseInt(temp / 10);
}
return sum === num;
};
const findAllArmstrong = ([start, end]) => {
const res = [];
for(let i = start; i <= end; i++){
if(isArmstrong(i)){
res.push(i);
};
};
return res;
};
console.log(findAllArmstrong(range));输出结果以下是控制台输出-
[ 153, 370, 371, 407 ]