水仙花数

编写程序计算所有N位水仙花数。(eg:153 = 1^3+5^3+3^3)

#include<iostream>    
using namespace std;

int main()
{
    int n;
    cin >> n;
    int first = 1;
    int i = 1;
    while(i<n){            //  求第一个要遍历的值,如n=3,则要遍历100-999
        first *= 10;
        i++;
    }
    i = first;
    while (i < first * 10) {         //  遍历
        int t = i;
        int sum = 0;
        while (t>0) {                  //整数的分解
            int a = t % 10;
            t /= 10;
            int b = a;
            int j = 1;
            while (j < n) {          //  求一个数n次幂
                b *= a;
                j++;
            }
            sum += b;           //   将各位的n次幂都加起来
        }
        if (sum == i)                         //   符合水仙花数,则打印
            cout << i << endl;
        i++;                                    //   自增,判断下一个数
    }
    system("pause");
}

 

posted @ 2018-09-02 14:19  朴者  阅读(192)  评论(0编辑  收藏  举报