Number of ways to arrange K different objects taking N objects at a time | Python3 implementation of the approach ; Function to return n ! % p ; res = 1 Initialize result ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; 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 ; Returns n ^ ( - 1 ) mod p ; Returns nCr % p using Fermat 's little theorem. ; Base case ; Fifactorial array so that we can find afactorial of r , n and n - r ; Function to return the number of ways to arrange K different objects taking N objects at a time ; Drivers Code ; Function call
mod = 10 ** 9 + 7 NEW_LINE def factorial ( n , p ) : NEW_LINE INDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT res = ( res * i ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def power ( x , y , p ) : NEW_LINE INDENT while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def modInverse ( n , p ) : NEW_LINE INDENT return power ( n , p - 2 , p ) NEW_LINE DEDENT def nCrModP ( n , r , p ) : NEW_LINE INDENT if ( r == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT fac = [ 0 for i in range ( n + 1 ) ] NEW_LINE fac [ 0 ] = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT fac [ i ] = fac [ i - 1 ] * i % p NEW_LINE DEDENT return ( fac [ n ] * modInverse ( fac [ r ] , p ) % p * modInverse ( fac [ n - r ] , p ) % p ) % p NEW_LINE DEDENT def countArrangements ( n , k , p ) : NEW_LINE INDENT return ( factorial ( n , p ) * nCrModP ( k , n , p ) ) % p NEW_LINE DEDENT N = 5 NEW_LINE K = 8 NEW_LINE print ( countArrangements ( N , K , mod ) ) NEW_LINE