實驗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 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM