Issues into
Title Description
The input values a, n, b, find (A n- value)% b of. Wherein a, b, n * n is a long integer.
Input Format
Three integers a, n, b.
Output Format
Output "a ^ n mod b = s"
s is the result of the operation
Sample input and output
Entry
2 10 9
Export
2^10 mod 9=7
problem analysis
For this problem, we first need to have mathematical knowledge base
(a*b)%k=(a%k)*(b%k)%k
Obviously, we can break down the number of times n.
A n , if n is even, A n = A n / 2 * A n / 2 ; if n is odd, A n = A n / 2 * A n / 2 * A. We claim i.e. only the A n-/ 2 , can be obtained by one multiplication A n- value. Continues to A n / 2 decomposition eventually becomes n 1. This is the dichotomy of thinking, therefore, we need only logn times can become the b 1. This is what we call the power of fast, recursive and non-recursive writing.
[Recursive]
. 1 int quickPow ( int A, int n-, int B)
2 {
. 3 IF (n-== . 1 ) return A;
. 4
. 5 IF (! (& N- . 1 )) // even, the bit operation priority attention, to brackets
6 {
. 7 int T = quickPow (A, n-/ 2 , B);
. 8 return T * T% B;
. 9 }
10
. 11 the else
12 is {
13 is int T = quickPow (A, n-/ 2 , B);
14 t=t*t%b;
15 t=t*a%b;
16 return t;
17 }
18 }
[Non-recursive]
1 int quickPow(int a,int n,int b)
2 {
3 int res=1;
4 while(n)
5 {
6 if(n&1)res=res*a%b;
7 a=a*a%b;
8 n>>=1;
9 }
10 return res;
11 }