1. 程式人生 > >HDU1163 Eddy's digital Roots【快速模冪+九餘數定理+水題】

HDU1163 Eddy's digital Roots【快速模冪+九餘數定理+水題】

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 84156    Accepted Submission(s): 26272


Problem Description The digital root of a positive integer is found by summing the digits of the integer. If the resulting value is a single digit then that digit is the digital root. If the resulting value contains two or more digits, those digits are summed and the process is repeated. This is continued as long as necessary to obtain a single digit.

For example, consider the positive integer 24. Adding the 2 and the 4 yields a value of 6. Since 6 is a single digit, 6 is the digital root of 24. Now consider the positive integer 39. Adding the 3 and the 9 yields 12. Since 12 is not a single digit, the process must be repeated. Adding the 1 and the 2 yeilds 3, a single digit and also the digital root of 39.

Input The input file will contain a list of positive integers, one per line. The end of the input will be indicated by an integer value of zero.

Output For each integer in the input, output its digital root on a separate line of the output.

Sample Input 24 39 0
Sample Output 6 3
Source

問題分析:

  這個問題是對於輸入的n,計算n^n的數根。給出兩種解題思路如下:

  解法一:

  先看一下以下式子:

  因為:(10*a+b)*(10*a+b)=100*a*a+10*2*a*b+b*b 

  所以右邊式子的數根(中間結果,也是左邊式子的數根)為:a*a+2*a*b+b*b=(a+b)*(a+b)

  故:對於兩位數n,n*n的數根=n的樹根×n的樹根。

  同理可以推出,對於任意位數的n,也滿足:n*n的數根=n的樹根×n的樹根。 

  程式中,實現一個計算整數數根的函式,利用這個函式來計算n^n的數根。

  解法二:

  計算n^n的數根,一要快,二要簡單。使用快速模冪計算,加上數論中的九餘數定理就完美了。


AC的C++語言程式如下(解法二):

/* HDU1163 Eddy's digital Roots */

#include <iostream>

using namespace std;

const int NICE = 9;

// 快速模冪計算函式
int powermod(int a, int n, int m)
{
    int res = 1;
    while(n) {
        if(n & 1) {        // n % 2 == 1
            res *= a;
            res %= m;
        }
        a *= a;
        a %= m;
        n >>= 1;
    }
    return res;
}

int main()
{
    int n, ans;

    while(cin >> n && n) {
        ans = powermod(n, n, NICE);
        cout << (ans ? ans : 9) << endl;
    }

    return 0;
}

 

AC的C語言程式如下(解法一):

/* HDU1163 Eddy's digital Roots */

#include <stdio.h>

// 計算數根函式
int digitalroots(int val)
{
    int result, temp;

    while(val) {
        result = 0;
        temp = val;

        while(temp) {
            result += temp % 10;
            temp /= 10;
        }

        if(result < 10)
            break;

        val = result;
    }

    return result;
}

int main(void)
{
    int n, ans, nr, i;

    while(scanf("%d", &n) != EOF) {
        if(n == 0)
            break;

        // 計算n的數根
        ans = nr = digitalroots(n);

        // 計算n^n的數根
        for(i=2; i<=n; i++) {
            ans = digitalroots(ans * nr);
        }

        // 輸出結果
        printf("%d\n", ans);
    }

    return 0;
}