快速幂取模

利用二进制扫描的方法快速的计算ab mod c,显然用常规方法计算74237 mod 4233计算量过大。

基本原理:(a×b)mod c=((a mod c)×b)mod c

例如:35 mod 7=3(101)2 mod 7=((3(100)2 mod 7)×3)mod 7=((9(10)2 mod 7)×3)mod 7=(((9 mod 7)(10)2 mod 7)×3)mod 7=((2(10)2 mod 7)×3)mod 7=((4(1)2 mod 7)×3)mod 7=(4×3)mod 7=5

 题目:Monkeys

Description

Have you heard of The Theory of Infinite Monkey ? Infinite monkeys hit keyboards randomly for infinite time, at last all books in the national library of France will be typed. Now, we assume that there are infinite monkeys sitting in front of keyboards and every keyboard has a ( 0 <= a < 100 ) key(s).We want to know how many different strings will be typed after every monkey hit the keyboard b ( 0 <= b < 10^9 ) time(s).You can suppose the monkey hit the keyboard randomly.The answer may be very large , so we want the answer mod c ( 10^6 < c < 10^7 ).

Input

The test will include many cases.Every case just have one line with three integer a,b,c.Notice that the test ended with c = 0,and you will not process it.

Output

Just one line with your answer .

Sample Input


1 1 2000000
2 2 2000000
1 1 0

Sample Output


1
4

 

int exp_mod(int a,int b,int n){
     int r=1;
     while(b){
         if(b&1)r=(r*a)%n;
         a=(a*a)%n;
         b>>=1;        
     }
     return r;
 }


时间复杂度分析:若a、b、n都是β位数,则所需算术运算的次数是O(β),所需位操作总次数是O(β3)

你可能感兴趣的:(快速幂取模)