Compute n ! under modulo p | C ++ program to comput n ! % p using Wilson 's Theorem ; Utility function to do modular exponentiation . It returns ( x ^ y ) % p ; int res = 1 ; Initialize result x = x % p ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; Function to find modular inverse of a under modulo p using Fermat 's method. Assumption: p is prime ; Returns n ! % p using Wilson 's Theorem ; n ! % p is 0 if n >= p ; Initialize result as ( p - 1 ) ! which is - 1 or ( p - 1 ) ; Multiply modulo inverse of all numbers from ( n + 1 ) to p ; Driver method
#include <bits/stdc++.h> NEW_LINE using namespace std ; int power ( int x , unsigned int y , int p ) { while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } int modInverse ( int a , int p ) { return power ( a , p - 2 , p ) ; } int modFact ( int n , int p ) { if ( p <= n ) return 0 ; int res = ( p - 1 ) ; for ( int i = n + 1 ; i < p ; i ++ ) res = ( res * modInverse ( i , p ) ) % p ; return res ; } int main ( ) { int n = 25 , p = 29 ; cout << modFact ( n , p ) ; return 0 ; }