您的位置:首页 > 其它

HDU 1163 Eddy's digital Roots(九余数定理+快速幂)

2015-07-24 21:10 453 查看


Eddy's digital Roots

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 5161 Accepted Submission(s): 2883



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.

The Eddy's easy problem is that : give you the n,want you to find the n^n's digital Roots.



Input

The input file will contain a list of positive integers n, one per line. The end of the input will be indicated by an integer value of zero. Notice:For each integer in the input n(n<10000).



Output

Output n^n's digital root on a separate line of the output.



Sample Input

2
4
0




Sample Output

4
4




九余数法,也叫弃九法,可以用来求一个数的弃九数,也能叫“根数”(即求这个数所有位的数的和,如果不是10以内的数,就重复这个过程,直到变成10以内的数,比如128的结果就是2,首先把128中的1,2,8相加得到11,再把11的1,1相加得2),求弃九数的方法就是拿这个数对9取模,若为0则弃九数是9,否则为余数。

更进一步可以用来验算加减运算是否正确,比如1863+716=2579,首先1863的弃九数为9,716弃九数为5,2579弃九数为4,因为(9+5)%9=4,所以加法运算很可能正确(注意!仅仅是很可能!正确概率约为8/9),再如3413-2546=867,依次计算出三者弃九数分别为2,8,3,即验算2-8=3,因为2小于8,所以要验算这个(2+9)-8=3,得出结论:运算很可能正确。

顺带一提,乘积的弃九数等于弃九数的乘积的弃九数。比如123*45*82的结果453873的弃九数为9,三者的弃九数6、9、9的乘积486的弃九数为9。

九余数法用到了数论中的一个性质:任意一个非零的n进制整数mod(n-1)后的数根与原数的数根相同。

这道题由于n不大,所以一般方法也能过,但也能用快速幂。

#include<cstdio>//非快速幂代码
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF&&n)
    {
        int ans=1,cnt=n;
        while(cnt--)
        {
            ans*=n;
            ans%=9;
        }
        printf("%d\n",ans?ans:9);
    }
    return 0;
}


#include<cstdio>//快速幂代码
int fastmod(int b,int c,int mod)
{
    int re=1,base=b;
    while(c)
    {
        if(c&1)
            re=((re%mod)*(base%mod))%mod;
        base=((base%mod)*(base%mod))%mod;
        c>>=1;
    }
    return re;
}
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF&&n)
    {
        int ans=fastmod(n,n,9);
        printf("%d\n",ans?ans:9);
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: