Find remainder when a number A raised to N factorial is divided by P | Function to calculate ( A ^ N ! ) % P in O ( log y ) ; Initialize result ; Update x if it is more than or Equal to p ; In case x is divisible by p ; ; If y is odd , multiply x with result ; y must be even now ; Returning modular power ; Function to calculate resultant remainder ; Initializing ans to store final remainder ; Calculating remainder ; Returning resultant remainder ; Given Input ; Function Call
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 >> 1 ; x = ( x * x ) % p ; } return res ; } function remainder ( n , a , p ) { let ans = a % p ; for ( let i = 1 ; i <= n ; i ++ ) ans = power ( ans , i , p ) ; return ans ; } let A = 2 , N = 1 , P = 2 ; document . write ( remainder ( N , A , P ) + " " ) ;