xy mod m = (x mod m)(y mod m) mod m
Instead of doing the multiplication first and then mod-ing, we can mod first to keep the number relatively small. Use this to implement a procedure that computes
be mod m | = | (be-1 × b) mod m | (algebra) |
= | (be-1 mod m)(b mod m) mod m | (above property) | |
= | (be-1 mod m)b mod m | (simplify) |
be mod m
as(be-1 mod m)b mod m.
Since this is defined recursively, multiplications will be put "on hold", and after each multiplication, a mod will be performed.