实验4-2-5 水仙花数 (20 分)

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

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

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

输入样例:
3

输出样例:
153
370
371
407

 1 #include<stdio.h>
 2 #include<math.h>
 3 
 4 //判断是否是水仙花数,如果是则输出1
 5 int narcissistic( int number ){
 6     int x = number, y = number, n = 0, sum = 0;
 7     while(x>0){
 8         n++;
 9         x /= 10;
10     }
11     while(y > 0){
12         sum += pow(y%10,n);
13         y /= 10;
14     }
15     if(sum == number){
16         return 1;
17     }
18     else{
19         return 0;
20     }
21 }
22 
23 //输出[m, n)范围内的水仙花数
24 void PrintN( int m, int n ){
25     for(int i = m; i < n; i++){
26         if(narcissistic(i)){
27             printf("%d\n", i);
28         }
29     }
30 }
31 
32 int main(){
33     int n;
34     scanf("%d", &n);
35     PrintN (pow(10,n-1), pow(10,n));
36     return 0;
37 }

猜你喜欢

转载自www.cnblogs.com/xiaolitongxueyaoshangjin/p/12105213.html
今日推荐