#11243: 使用建表方式提升速度 (4ms, 80KB)


avengertree (否放)

學校 : 大葉大學
編號 : 28345
來源 : [106.105.103.37]
最後登入時間 :
2021-08-01 20:13:54
a040. 阿姆斯壯數 | From: [36.227.50.14] | 發表日期 : 2016-08-06 20:12

#include <iostream>
#include <cstring>
using namespace std;
 
int numberList[10][8]={
    {0,0,0,0,0,0,0,0},
    {1,1,1,1,1,1,1,1},
    {1,2,4,8,16,32,64,128},
    {1,3,9,27,81,243,729,2187},
    {1,4,16,64,256,1024,4096,16384},
    {1,5,25,125,625,3125,15625,78125},
    {1,6,36,216,1296,7776,46656,279936},
    {1,7,49,343,2401,16807,117649,823543},
    {1,8,64,512,4096,32768,262144,2097152},
    {1,9,81,729,6561,59049,531441,4782969}
};
int useNum[10],digit;
//計算幾位數字
void calculate(int inum)
{
    while (inum>0)
    {
        useNum[inum%10]++;
        digit++;
        inum/=10;
    }
}
//計算是否相等
void equal(int inum , bool& have_n)
{
    int sum=0,i;
    for (i=9 ; i>0 ; i--)
    {
        sum = sum + (numberList[i][digit]*useNum[i]);
        if (sum > inum)break;
    }
 
    if (sum == inum)
    {
        if (have_n)cout << " ";
        cout << inum;
        have_n=true;
    }
}
int main()
{
    int n,m;
    while (cin >> n >> m)
    {
        bool have_num=false;
        while (n <= m)
        {
            memset(useNum , 0 , 10*sizeof(int));
            digit=0;
            calculate(n);
            equal(n , have_num);
            n++;
        }
        if (!have_num)cout << "none";
        cout << endl;
    }
return 0;
}
 
ZeroJudge Forum