首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

水仙花數(阿姆斯特朗數)C語言求解:輸出 10000 以內所有水仙花數

     編輯:程式設計綜合問答

定義回顧

水仙花數是指一個 n 位數(n ≥ 3),其各位數字的 n 次冪之和等於該數本身。例如:153 = 1³ + 5³ + 3³。

算法思路

  1. 遍歷 100 到 9999(四位數最大 9999,五位數最小 10000 不在範圍內)。
  2. 對每個數計算位數 n,分解各位數字,計算 n 次冪和。
  3. 若和等於原數,輸出。

完整 C 代碼

#include <stdio.h>
#include <math.h>

int isNarcissistic(int num) {
    int original = num;
    int n = 0;
    int temp = num;
    // 計算位數
    while (temp > 0) {
        n++;
        temp /= 10;
    }
    // 位數 < 3 直接返回 false
    if (n < 3) return 0;

    int sum = 0;
    temp = num;
    while (temp > 0) {
        int digit = temp % 10;
        sum += (int)pow(digit, n);
        temp /= 10;
    }
    return sum == original;
}

int main() {
    printf("10000 以內的水仙花數:\n");
    for (int i = 100; i < 10000; i++) {
        if (isNarcissistic(i)) {
            printf("%d ", i);
        }
    }
    printf("\n");
    return 0;
}

運行結果

10000 以內的水仙花數:
153 370 371 407 1634 8208 9474

知識擴展

  • 三位數水仙花數只有 4 個:153、370、371、407。
  • 四位數水仙花數(四葉玫瑰數)有 3 個:1634、8208、9474。
  • 五位數及以上同理,但數量極少,計算量隨位數指數增長。

優化提示

  • 預計算 0-9 的各次冪值存入查表數組,避免重複調用 pow()。
  • 利用數學性質縮小搜索範圍(如 n 位數最大和為 n×9n,超過 10n-1 即無解)。

參考百度知道解法:鏈接(將 1000 改為 10000 即可)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved