九余数定理
(a+b)%p = (a%p+b%p)%p;
(a-b)%p = (a%p-b%p)%p;
(ab)%p = (a%pb%p)%p;
(a^b)%p = ((a%p)^b)%p;
1234%9=(1%91000%9+2%9100%9+3%910%9+4%9)%9=(1+2+3+4)%9;
出现这种状况的原因的是10的倍数对9取余为1,
例如1000=9111+1 , 100=911+1 , 10=91+1;
即:一个整数模9的结果与这个整数的各位数字之和模9的结果相同
应用:快速求数根的计算方法。
For a positive integer n, let f(n) denote the
sum of the digits of n when represented in base
10. It is easy to see that the sequence of numbers n, f(n), f(f(n)), f(f(f(n))), . . . eventually
becomes a single digit number that repeats forever. Let this single digit be denoted g(n).
For example, consider n = 1234567892.
Then:
f(n) = 1+2+3+4+5+6+7+8+9+2 = 47
f(f(n)) = 4 + 7 = 11
f(f(f(n))) = 1 + 1 = 2
Therefore, g(1234567892) = 2.
Input
Each line of input contains a single positive integer n at most 2,000,000,000. Input is terminated
by n = 0 which should not be processed.
Output
For each such integer, you are to output a single
line containing g(n).
Sample Input
2
11
47
1234567892
0
Sample Output
2
2
2
2
#include <stdio.h>
int main(){
int sum=0;
char a;
while(a=getchar()){
if(a=='\n'){
if(!sum) return 0;
printf("%d\n",sum%9?sum%9:9);
sum=0;
}
else if(a>='0' && a<='9'){
sum+=a-'0';
}
}
return 0;
}
posted on
浙公网安备 33010602011771号