一段範圍內阿姆斯特朗數 - JavaScript
如果對於一個數字,有以下等式成立,則這個數字被稱為阿姆斯特朗數 −
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 ]
廣告