#NEWLINE# def fast_exponentiation( a , p , n ) : #NEWLINE# #INDENT# 'Calculates r = a^p mod n\n    ' #NEWLINE# result = ( a % n ) #NEWLINE# remainders = [ ] #NEWLINE# while ( remainders != 1 ) : #NEWLINE# #INDENT# remainders . append ( ( p & 1 ) ) #NEWLINE# p = ( p >> 1 ) #NEWLINE# #UNINDENT# while remainders : #NEWLINE# #INDENT# rem = remainders . pop ( ) #NEWLINE# result = ( ( ( a ** rem ) * ( result ** 2 ) ) % n ) #NEWLINE# #UNINDENT# return result