def fast_exponentiation(a, p, n):
 result = (a % n)
 remainders = []
 while (p != 1):
  remainders.append((p & 1))
  p = (p >> 1)
 while remainders:
  rem = remainders.pop()
  result = (((a ** rem) * (result ** 2)) % n)
 return result

def fast_exponentiation ( a , p , n ) : result = ( a % n ) remainders = [ ] while ( p != 1 ) : remainders . append ( ( p & 1 ) ) p = ( p >> 1 ) while remainders : rem = remainders . pop ( ) result = ( ( ( a ** rem ) * ( result ** 2 ) ) % n ) return result
calculates r = a^p mod n .