Modular Exponentiation ( Power in Modular Arithmetic ) | Iterative Function to calculate ( x ^ y ) in O ( log y ) ; Initialize answer ; If y is odd , multiply x with result ; y = y / 2 ; Change x to x ^ 2
int power ( int x , int y ) { int res = 1 ; while ( y ) { if ( y % 2 == 1 ) res = ( res * x ) ; y = y >> 1 ; x = ( x * x ) ; } return res ; }