題目:
? ??打印出所有的水仙花數(shù)
水仙花數(shù)
????水仙花數(shù)(Narcissistic number)也被稱為超完全數(shù)字不變數(shù)(pluperfect digital invariant, PPDI)杭煎、?自戀數(shù)、自冪數(shù)蔫磨、阿姆斯壯數(shù)或阿姆斯特朗數(shù)(Armstrong number)蝙昙,水仙花數(shù)是指一個(gè) n 位數(shù)(n≥3 ),它的每個(gè)位上的數(shù)字的 n 次冪之和等于它本身(例如:1^3 + 5^3+ 3^3 = 153)。
? ??水仙花數(shù)只是自冪數(shù)的一種鱼响,嚴(yán)格來(lái)說(shuō)3位數(shù)的3次冪數(shù)才稱為水仙花數(shù)。
? ??附:其他位數(shù)的自冪數(shù)名字
? ??一位自冪數(shù):獨(dú)身數(shù)
? ??兩位自冪數(shù):沒(méi)有
? ??三位自冪數(shù):水仙花數(shù)
? ??四位自冪數(shù):四葉玫瑰數(shù)
? ??五位自冪數(shù):五角星數(shù)
? ??六位自冪數(shù):六合數(shù)
? ??七位自冪數(shù):北斗七星數(shù)
? ??八位自冪數(shù):八仙數(shù)
? ??九位自冪數(shù):九九重陽(yáng)數(shù)
? ??十位自冪數(shù):十全十美數(shù)
JavaScript
? ? 解題時(shí)组底,先寫測(cè)試函數(shù),再寫查找函數(shù)
? ??// 測(cè)試函數(shù)
????// 測(cè)試每一個(gè)數(shù)
function testResultItem(n){
? // 水仙花數(shù)是三位數(shù)
? if(n<100 || n>=1000){
? ? return false
? }
? let a = Number.parseInt(n / 100)
? let b = Number.parseInt((n % 100) / 10)
? let c = n % 10
? let sum = Math.pow(a, 3)+Math.pow(b, 3)+Math.pow(c, 3)
? if(sum != n){
? ? return false
? }
? return true
}
????// 測(cè)試數(shù)組
function testArr(arr){
? let flag = true
? if(!Array.isArray(arr) || arr.length == 0){
? ? flag = false
? ? return flag
? }
for(let i=0; i<arr.length; i++){
? ??if(!testResultItem(arr[i])){
? ? ? flag = false
? ? ? break
? ? }
}
????return flag
}
// 編程函數(shù)
function judgeItem(n){
? let a = Math.floor(n / 100 )
? let b = Math.floor((n % 100) / 10)
? let c = n % 10
? let sum = Math.pow(a, 3)+Math.pow(b, 3)+Math.pow(c, 3)
? if(sum != n){
? ? return false
? }
? return true
}
function findNarFunc(){
? let results = []
? for(let i=100; i<1000; i++){
? ? if(judgeItem(i)){
? ? ? results.push(i)
? ? }
? }
? return results
}
let arr1 = findNarFunc()
console.log(arr1)
console.log(testArr(arr1))
? ? (內(nèi)容來(lái)自百度百科)