a040. 阿姆斯壯數

解法一、窮舉

✅ 完整代碼

評分結果(參考) : AC (31ms, 348KB)

#include <bits/stdc++.h>
using namespace std;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    
    int a, b;
    cin >> a >> b;

    bool space = false;
    for(int i=a; i<=b; i++){
        int digit = log10(i) + 1;
        
        int temp=i, sum=0;
        while(temp != 0){
            sum += pow(temp%10, digit);
            temp /= 10;
        }
        
        if(sum == i){
            if(space) cout << " ";
            space = true;
            cout << i;
        }
    }
    
    if(!space) cout << "none";

    return 0;
}

解法二、查表

🔹 建表

會發現 阿姆斯壯數 的條件有些嚴格
1 ~ 1000000 實際上沒有幾個 阿姆斯壯數

運行 解法一 的代碼輸入 1 1000000
複製輸出,儲存到陣列中

✅ 完整代碼

評分結果(參考) : AC (2ms, 348KB)

#include <bits/stdc++.h>
using namespace std;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    
    int a, b;
    bool find = false;
    cin >> a >> b;

    vector<int> armstrongNum = {
        1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407,
        1634, 8208, 9474, 54748, 92727, 93084, 548834
    };

    for(int i : armstrongNum){
        if(i > b) break;
        if(i >= a){
            cout << i << " ";
            find = true;
        }
    }

    if(!find) cout << "none";

    return 0;
}