Eddy’s digital Roots
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
题目大意:求N^N的数字根。
之前做过一个类似的[杭电1013](
https://blog.csdn.net/BarisGuo/article/details/82049985),不同的是杭电1013将那个数字用字符串形式给了你,而这道题却需要你自己算。死算是不可能算出来的,所以必须找规律。之后我发现将n*n不断取数字根相乘所得结果便是n^n的数字根。得此代码:
#include<stdio.h>
int f(int x){ /*计算数字根*/
while(x>=10)
x=x/10+x%10;
return x;
}
int main()
{
int n,i,root;
while(scanf("%d",&n)!=EOF){
if(n==0)break;
root=f(n);
for(i=1;i<n;i++)
root=n*f(root);
root=f(root);
printf("%d\n",root);
}
return 0;
}
之后借鉴他人所作,才知晓此处运用了九余数定理,即一个数的树根等于该数对九的余数。如此一来,代码就更简单了:
#include<stdio.h>
int main()
{
int n,a;
while(scanf("%d",&n)!=EOF){
a=1;
for(int i=0;i<n;i++)
a=a * n % 9;
if(a==0) a=9;
printf("%d\n",a);
}
}