最近在網路上有人提出一個問題,
使用者輸入二個數,並求這二個數之間所有的 "阿姆斯壯數"
阿姆斯壯數?? 一開始提問者的說明讓我覺得很模糊,後來我找了一下資料
要說明其實還是列下面幾點比較清楚...

1. 假設數字 X 是 n 位元的數字,其內容為 X1X2....Xn

2. 如果 X1^n + X2^n +..... +Xn^n = X

那麼 X 就是阿姆斯壯數。
講完了,還是很模糊對不對?直接帶二個數字給大家就知道了..

153 (有三位數) = 1^3 + 5^3 + 3^3 = 153 ,所以153是阿姆斯壯數
1634(有四位數) = 1^4 + 6^4 + 3^4 + 4^4 = 1634,所以1634也是阿姆斯壯數

其實這題目還蠻無聊的,就只有使用 %、/ 指令而已
很無奈的 C 語言裡面的 math.h 的 pow() 函數只支援 float 、double,
所以只好再寫一個 power() 是用 unsigned long 的函數..


以下為程式碼,寫成提問者想要的型式
其中比較有價值的函數也只有bool IsArmstrongNumber(unsigned long n);
參考就好...

 

// ====================================
// FileName: ArmstrongNumber.cpp
// Author  : Edison.Shih.
// Complier: VC 2008

#include <stdio.h>
#include <stdlib.h>

// ====================================
// power, no use math.h, because return unsigned long.
// a^b
unsigned long power(unsigned long a, unsigned long b)
{
        unsigned long i=0;
        unsigned long result = 1;
        for(i=0; i<b; i++){
                result = result*a;
        }
        return result;
}

// ====================================

bool IsArmstrongNumber(unsigned long n){
        unsigned long temp = n;
        unsigned long dig_cnt = 0;
        unsigned long i=0;

        // cal dig_cnt
        while(temp!=0) {
                temp = temp/10;
                dig_cnt++;
        }

        // judge n is ArmstrongNumber or not.
        temp = n;
        unsigned long power_sum=0;
        for(i=0; i<dig_cnt; i++){
                power_sum = power_sum + power(temp%10, dig_cnt);
                temp = temp / 10;
        }
       
        if(power_sum == n) return true;
        else return false;       
}

// ====================================
// main function
int main(int argc, char **argv)
{
        unsigned long low=0, up=0, i=0;
        bool find_flag = false;
        printf("please input the lower number:");
        scanf("%lu", &low);
        printf("please input the upper number:");
        scanf("%lu", &up);
        for(i=low; i<=up; i++){
                if(IsArmstrongNumber(i)) {
                        printf("%lu\n", i);
                        find_flag = true;
                }
        }
        if(!find_flag) printf("can't Armstrong Number between %lu and %lu\n", low, up);
        system("pause");
        return 0;
}
// ====================================

執行結果如下

ArmstrongNumber.jpg 

 

 

arrow
arrow
    全站熱搜

    Edison 發表在 痞客邦 留言(1) 人氣()