您的位置:首页 > 其它

快速幂定理和九余数定理(Eddy's digital Roots)

2015-10-11 10:43 447 查看
题目描述:

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.

这道题运用九余数定理和快速幂定理可以很好的完成。

九余数定理:一个数各位数字之和等于这个数对9取模所得的数。

快速幂定理:假设是求a的b次方。



下面是快速幂定理的C代码实现:

int quick_pow( int a, int b ){
int r = 1, base = a;
while( b != 0 ){
if( b&1 ){  //取 b 二进制的最低位
r *= base;
}
base *= base;  //幂次控制器
b>>=1;   //将 b 的二进制位右移一位
}
return r;
}


有了这两个定理,下面我们就可以运用这两个定理来解析这道题了。

int quick_p_9( int a, int b, int mod ){
int rs = 1, base = a;
while( b != 0 ){
if( b & 1 ){
rs = ( rs * (base%mod) ) % mod;
}
base = ( (base%mod) * (base%mod) )%mod;
b >>= 1;
}
return rs;
}

int main()
{
int n;
while( cin>>n && n != 0 ){
int ans = quick_p_9(n,n,9);
cout<<( ans == 0 ? 9 : ans )<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: