Số Armstrong thỏa mãn: xy..z = x^n + y^n + ... + z^n (n là số chữ số).
Ví dụ: 370 = 3^3 + 7^3 + 0^3 = 27 + 343 + 0 = 370.
Viết hàm tìm tất cả số Armstrong trong khoảng [lower, upper].
Ví dụ
Mã thực hiện:
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));
Kết quả
Kết quả in ra console:
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371 ]