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 ]
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志