A ^ B mod C
Time Limit: 1 s |
Memory limit: 32 m |
Accepted submit: 68 |
Total submit: 376 |
Problem description
Given a, B, c, you shoshould quickly calculate the result of a ^ B mod C. (1 <= A, B, C <2 ^ 63 ).
Input
There are multiply testcases. Each testcase, there is one line contains three integers A, B and C, separated by a single space.
Output
For each testcase, output an integer, denotes the result of a ^ B mod C.
Sample Input
3 2 42 10 1000 Sample output
124
Original: fzu 2009 Summer Training IV -- Number Theory
|
Solution:
Powerful questions. We need to consider that the data is too large and may overflow during data processing. Collect and repost some good articles on the modulo power operation. In the next article. (The following code can pass fzu 1650, but 1650 of the Code may not pass 1752 .)
# Include <stdio. h> </P> <p> unsigned long MUL (unsigned long a, unsigned long B, unsigned long C) <br/>{< br/> unsigned long ret = 0, TMP = A % C; <br/> while (B) <br/> {<br/> If (B & 0x1) <br/> If (Ret + = TMP)> = C) <br/> ret-= C; <br/> If (TMP <= 1)> = C) <br/> TMP-= C; <br/> B >>= 1; <br/>}< br/> return ret; <br/>}</P> <p> unsigned long Mod (unsigned long a, unsigned long B, unsigned long c) <B R/>{< br/> unsigned long y = 1; <br/> while (B) <br/>{< br/> If (B & 1) <br/> Y = MUL (Y, a, c); <br/> A = MUL (a, a, c ); <br/> B = B> 1; <br/>}< br/> return y; <br/>}</P> <p> int main () <br/>{< br/> unsigned long a, B, c; <br/> while (scanf ("% LlU", &, & B, & C )! = EOF) <br/> printf ("% LlU/N", MOD (A, B, C); <br/> return 0; <br/>}