Number of ways to arrange K different objects taking N objects at a time | PHP 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 ; Fill factorial array so that we can find all factorial of r , n and n - r ; Function to return the number of ways to arrange K different objects taking N objects at a time ; Driver Code ; Function call
< ? php $ mod = ( 1e9 + 7 ) ; function factorial ( $ n , $ p ) { for ( $ i = 2 ; $ i <= $ n ; $ i ++ ) $ res = ( $ res * $ i ) % $ p ; return $ res ; } function power ( $ x , $ y , $ p ) { while ( $ y > 0 ) { if ( ( $ y & 1 ) == 1 ) $ res = ( $ res * $ x ) % $ p ; $ x = ( $ x * $ x ) % $ p ; } return $ res ; } function modInverse ( $ n , $ p ) { return power ( $ n , $ p - 2 , $ p ) ; } function nCrModP ( $ n , $ r , $ p ) { if ( $ r == 0 ) return 1 ; $ fac = array ( ( int ) $ n + 1 ) ; $ fac [ 0 ] = 1 ; for ( $ i = 1 ; $ i <= $ n ; $ i ++ ) $ fac [ $ i ] = $ fac [ $ i - 1 ] * $ i % $ p ; return ( $ fac [ ( int ) $ n ] * modInverse ( $ fac [ ( int ) $ r ] , $ p ) % $ p * modInverse ( $ fac [ ( int ) $ n - ( int ) $ r ] , $ p ) % $ p ) % $ p ; } function countArrangements ( $ n , $ k , $ p ) { return ( factorial ( $ n , $ p ) * nCrModP ( $ k , $ n , $ p ) ) % $ p ; } { $ N = 5 ; $ K = 8 ; echo ( countArrangements ( $ N , $ K , $ mod ) ) ; }