您的位置:首页 > 其它

HDU 1163 Eddy's digital Roots 【九余数定理 Or 规律(瞎搞)】

2017-02-06 19:41 573 查看
[align=left]Problem Description[/align]
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.

 

[align=left]Input[/align]
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).

 

[align=left]Output[/align]
Output n^n's digital root on a separate line of the output.

 

[align=left]Sample Input[/align]

2
4
0

 

[align=left]Sample Output[/align]

4
4

题意:求n的n次方的各位数之和,如果得到的和非小于十的数则继续执行此操作直至次数小于十。

这里有个定理叫做九余数定理,是这样的:一个数对九取余,得到的数称之为九余数,一个数的九余数等于它的各个数位上的数之和的九余数。因为不难证明所以此处不再给出证明了。   当然也有别的方法,比如暴力打表找规律,这里不做介绍了,有兴趣的可以去了解一下(突然发现这种平方又取模的很多都有规律可言啊~)

AC代码:

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
long long quickpow(long long a, long long b, long long c)
{
long long ans = 1;
a=a%c;
while (b)
{
if (b%2) //b为奇数
ans = (ans * a) % c;
b = b / 2;
a = (a*a) % c;  //(a^2)%c;
}
return ans;
}
int main()
{
long long n, ans;
while(~scanf("%lld",&n) && n)
{
ans = quickpow(n, n, 9);
if(ans == 0) ans = 9;
cout << ans << endl;
}
return 0;
}

                                                                                         
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: