Find remainder when a number A raised to N factorial is divided by P | package whatever do not write package name here ; 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 ; Driver Code ; Given Input ; Function Call
import java . io . * ; class GFG { static long power ( long x , long y , long p ) { long res = 1 ; x = x % p ; if ( x == 0 ) return 0 ; while ( y > 0 ) { if ( ( y & 1 ) == 1 ) res = ( res * x ) % p ; y = y >> 1 ; x = ( x * x ) % p ; } return res ; } static long remainder ( long n , long a , long p ) { long ans = a % p ; for ( long i = 1 ; i <= n ; i ++ ) ans = power ( ans , i , p ) ; return ans ; } public static void main ( String [ ] args ) { long A = 2 , N = 1 , P = 2 ; System . out . println ( remainder ( N , A , P ) ) ; } }