Eddy's digital RootsTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 7780 Accepted Submission(s): 4217 http://acm.hdu.edu.cn/showproblem.php?pid=1163 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.
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
|
九余数的定理:一个数对9取余等于这个数各位数相加的和对9取余。例如 123 %9 = (1+2+3)%9,然后也可以知道0-9(不包括0和9)任何数除9的余数都是等于本身比如:4%9=4.。所以想求数根,用九余数是很方便的。比如一个大于9的数除以9的余数,这个余数相当于0-9之间的某数除以9的余数(九余数定理)又因为4%9=4这个定理。更加确定树根即其余数
思路:就是把n^n对9取余。
代码:
#include<iostream>
#include<cstring>
#include<cmath>
#include<iomanip>
#define inf 0x3f3f3f3f
using namespace std;
int main()
{
int n,m;
while(cin>>n&&n)
{
m=n;
for(int i=2;i<=n;i++)
m=(m*n)%9; //九余数定理
if(m)
cout<<m<<endl;
else
cout<<"9"<<endl;
}
return 0;
}