Modular Exponentiation ( Power in Modular Arithmetic ) | Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now ; Driver Code
function power ( x , y , p ) { let res = 1 ; x = x % p ; if ( x == 0 ) return 0 ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % p ; y = $y / 2 y = y >> 1 ; x = ( x * x ) % p ; } return res ; } let x = 2 ; let y = 5 ; let p = 13 ; document . write ( " " + power ( x , y , p ) ) ;