Naive Algorithm: Compute
by
repeatedly multiplying by and reducing modulo . This is BAD
because it takes multiplications.
Clever Algorithm: The following observation is the key idea which
makes the clever algorithm work. Write
with
each
, i.e., write in base (binary).
Then
mod 100 | |||
0 | 91 | 1 | 6 |
1 | 45 | 1 | 36 |
2 | 22 | 0 | 96 |
3 | 11 | 1 | 16 |
4 | 5 | 1 | 56 |
5 | 2 | 0 | 36 |
6 | 1 | 1 | 96 |
Summary of above table: The first column,
labeled ,
is just to keep track of . The second column, labeled ,
is got by dividing
the entry above it by and taking the integer part of the result.
The third column, labeled
,
simply records whether or not the second column is
odd. The forth column is computed by squaring, modulo 100, the entry above
it.
Some examples in PARI to convince you that powering isn't too difficult:
? Mod(17,389)^5000 %13 = Mod(330, 389) ? Mod(2903,49084098)^498494 %14 = Mod(13189243, 49084098)These both take no noticeable time.