The main idea is to use a formula:A * B % C = (a % C) * (B % C) % C
Basic concepts and ideas
Operations on the form such as a ^ B mod m (B is generally large), but a, B, and m are all within the long range. Algorithm The main idea is to divide and conquer. Divide large problems into several similar small problems! The specific implementation is to use recursive methods! For example, 2 ^ 100mod 3, if we calculate the value of 2 ^ 100 first and then modulo 3, it is more difficult! We can change 100 to 2 ^ 100 = (2 ^ 50) ^ 2 = (2 ^ 25) ^ 2) ^ 2 = (2 ^ 1) ^ 2) ^ 2 )...) ^ 2 if we have obtained the value of 250 mod 3, we can easily get the value of 2 ^ 100mod 3. Continue with the analysis according to the above method... The final result will surely be 2 ^ 1mod 3! This is easy to handle! This is the recursive boundary. Now we can return the value of 2 mod 3! Another problem is that there are two cases of time-sharing! 2 ^ 100 = (2 ^ 50) 2,100 is an even number 2 ^ 99 = (2 ^ 49) 2*2, 99 is an odd number. In the second case, the base number must be higher than that in the first case.
Recursive AlgorithmsCodeAs follows:
1 Long MoD ( Long A, Long B, Long C) 2 { 3 Long Ans; 4 If (! B) Return 1 ; 5 Else If (B = 1) Return A % C; 6 Else Ans = Mod (a, B/ 2 , C ); 7 Ans = (ANS * ans) % C; 8 If (B & 1 ) Ans = (ANS * (a % C) % C; 9 Return Ans; 10 }
Another efficient algorithm is to replace recursive algorithms with loops.
1 Long Mod_loop ( Long A, Long B, Long C) 2 { 3 Long Ret = 1 , TEM =A; 4 While (B) 5 { 6 If (B & 1 ) Ret = RET * TEM % C; 7 TEM = TEM * TEM % C; 8 B> = 1 ; 9 } 10 Return RET; 11 }