I have been taught the Fast Modular Exponentiation Algorithm as shown below.
FastExponentiation(a, p, n):
if p = 0 then
return 1
if p is even then
t <- FastExponentiation(a, p/2, n)
return t^2 mod n
t <- FastExponentiation(a, (p-1)/2, n)
return a(t^2 mod n) mod n
How do the second and third return statements ever get reached when running this program? There is a recursive call before these two statements so surely the program would just enter a recursive loop?
The snippet below can illustrate you how
pdecreases while going deeper into the recursion, until it becomes1. On the next recursive call it becomes zero:(1-1)/2→0.