题目地址:http://ac.jobdu.com/problem.php?pid=1085
- 题目描述:
-
N<k时,root(N,k) = N,否则,root(N,k) = root(N',k)。N'为N的k进制表示的各位数字之和。输入x,y,k,输出root(x^y,k)的值 (这里^为乘方,不是异或),2=<k<=16,0<x,y<2000000000,有一半的测试点里 x^y 会溢出int的范围(>=2000000000)
- 输入:
-
每组测试数据包括一行,x(0<x<2000000000), y(0<y<2000000000), k(2<=k<=16)
- 输出:
-
输入可能有多组数据,对于每一组数据,root(x^y, k)的值
- 样例输入:
-
4 4 10
- 样例输出:
-
4
二分求幂参考:http://blog.csdn.net/prstaxy/article/details/8740838
快速幂取模参考:http://blog.sina.com.cn/s/blog_8619a25801010wcy.html, http://blog.csdn.net/yangyafeiac/article/details/8707079
#include <stdio.h> long long root (long long x, long long y, long long k){
long long ans = 1; while (y != 0){
if ((y & 1) == 1)
ans = (ans * x) % k;
x = (x * x) % k;
y = y >> 1;
}
return ans;
} int main(void){
long long x, y, k;
long long ans; while (scanf ("%lld %lld %lld", &x, &y, &k) != EOF){
ans = root (x, y, k-1);
if (ans == 0)
ans = k-1;
printf ("%lld\n", ans);
} return 0;
}