PTA水仙花数(C语言 + 详细注释)

水仙花数是指一个N位正整数(N≥3),它的每个位上的数字的N次幂之和等于它本身。例如:153=1​3​​+5​3​​+3​3​​。 本题要求编写程序,计算所有N位水仙花数。

输入格式:

输入在一行中给出一个正整数N(3≤N≤7)。

输出格式:

按递增顺序输出所有N位水仙花数,每个数字占一行。

输入样例:

3

输出样例:

153
370
371
407

#include <stdio.h>

int power(int m, int n);

int isDaffodinumber(int x, int digit);

int main(){

      int n, i;

      scanf("%d", &n);

      int lower = power(10, n - 1);     //找到下界

      int upper = power(10, n);          //找到上界

      for(i = lower; i < upper; i++){

            if(isDaffodinumber(i, n))

                 printf("%d\n", i);

       } 

       return 0;

}

int power(int a, int b){             //自写power函数或者调用pow函数(在math.h里面)

      int result = 1;

      while(b--)

            result *= a;

      return result;

}

int isDaffodinumber(int x, int digit){

       int sum = 0;   

       int t = x;             //用t代替x,操作t        

       do{

            sum += power(t % 10, digit);              // t % 10得到每一位

        }while(t /= 10);

        return (sum == x) ? 1 : 0;

}

发布了30 篇原创文章 · 获赞 10 · 访问量 401

猜你喜欢

转载自blog.csdn.net/qq_45472866/article/details/104055891