Number of ways to arrange K different objects taking N objects at a time | javascript implementation of the approach ; Function to return n ! % p ; var 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
var mod = parseInt ( 1e4 + 7 ) ; function factorial ( n , p ) { for ( var 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 ; var fac = Array . from ( { length : n + 1 } , ( _ , i ) => 0 ) ; ; fac [ 0 ] = 1 ; for ( var i = 1 ; i <= n ; i ++ ) fac [ i ] = fac [ i - 1 ] * i % p ; return ( fac [ parseInt ( n ) ] * modInverse ( fac [ parseInt ( r ) ] , p ) % p * modInverse ( fac [ parseInt ( n ) - parseInt ( r ) ] , p ) % p ) % p ; } function countArrangements ( n , k , p ) { return ( factorial ( n , p ) * nCrModP ( k , n , p ) ) % p ; } var N = 5 , K = 8 ; document . write ( countArrangements ( N , K , mod ) ) ;