ZJANS

a040. 阿姆斯壯數

Medium Last Update: 2025/05/16
基本運算

所謂 Armstrong number 指的是一個 n 位數的整數,它的所有位數的 n 次方和恰好等於自己
如:1634=14+64+34+441634 = 1^{4} + 6^{4} + 3^{4} + 4^{4}
給兩個數字 n, m
在 [n, m] 中找出所有的 Armstrong number


解法一、窮舉

✅ 完整代碼

評分結果(參考) : 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;
}