6-3 Quick Power (10 分)
The function Power
calculates the exponential function Nk. But since the exponential function grows rapidly, you are supposed to return (Nk)%10007instead.
Format of function:
int Power(int N, int k);
Both N
and k
are integers, which are no more than 2147483647.
Sample program of judge:
#include <stdio.h>
int Power(int, int);
const int MOD = 10007;
int main()
{
int N, k;
scanf("%d%d", &N, &k);
printf("%d\n", Power(N, k));
return 0;
}
/* Your function will be put here */
Sample Input 1:
2 3
Sample Output 1:
8
Sample Input 2:
128 2
Sample Output 2:
6377
快速幂取模
//积的取余等于取余的积的取余
(a*b) % m = pi;
((a%m)*(b%m)) % m = pj;
即证:
pi = pj;
0 < pi < m, 0 < pj < m;
证明如下:
1.a = m*x1 + p1;
2.b = m*x2 + p2;
3.(a%m)*(b%m) = p1*p2;
4.(a%m)*(b%m) = m*x3 + pj;
5.a*b = m*x1*m*x2 + p1*m*x2 + p2*m*x1 + p1*p2
6. = m*(m*x1*x2 + p1*m2 + p2*m1) + p1*p2;
7.a*b = m*x4 + pi;
8.6 & 3-- > a*b = m*(m*x1*x2 + p1*m2 + p2*m1) + (a%m)*(b%m);
9.4 & 8-- > a*b = m*(m*x1*x2 + p1*m2 + p2*m1 + x3) + pj;
10.9 & 7-- > m*(m*x1*x2 + p1*m2 + p2*m1 + x3) + pj = m*x4 + pi;
pj=pi,得证!
-->a的b次方 mod c = (a mod c)的b次方 mod c
//快速幂
直到b为1
具体操作代码如下
int Power(int N, int k) {
int n = 1;
N = N%MOD;
while (k > 0) {
if (k % 2 == 1)n = n*N%MOD;//当k为奇数时
k /= 2;
N = N*N%MOD;
}
return n;
}