Find ways to arrange K green balls among N balls such that exactly i moves is needed to collect all K green balls | Java implementation of the approach ; To store the factorial and the factorial mod inverse of a number ; Function to find ( a ^ m1 ) % mod ; Function to find factorial of all the numbers ; Function to find the factorial mod inverse of all the numbers ; Function to return nCr ; Function to find ways to arrange K green balls among N balls such that we need exactly i moves to collect all K green balls ; Driver code ; Function call
import java . util . * ; class GFG { static final int N = 100005 ; static final int mod = ( int ) ( 1e9 + 7 ) ; static long [ ] factorial = new long [ N ] ; static long [ ] modinverse = new long [ N ] ; static long power ( long a , int m1 ) { if ( m1 == 0 ) return 1 ; else if ( m1 == 1 ) return a ; else if ( m1 == 2 ) return ( 1L * a * a ) % mod ; else if ( m1 % 2 == 1 ) return ( 1L * a * power ( power ( a , m1 / 2 ) , 2 ) ) % mod ; else return power ( power ( a , m1 / 2 ) , 2 ) % mod ; } static void factorialfun ( ) { factorial [ 0 ] = 1 ; for ( int i = 1 ; i < N ; i ++ ) factorial [ i ] = ( 1L * factorial [ i - 1 ] * i ) % mod ; } static void modinversefun ( ) { modinverse [ N - 1 ] = ( int ) ( power ( factorial [ N - 1 ] , mod - 2 ) % mod ) ; for ( int i = N - 2 ; i >= 0 ; i -- ) modinverse [ i ] = ( 1 * modinverse [ i + 1 ] * ( i + 1 ) ) % mod ; } static long binomial ( int n , int r ) { if ( r > n ) return 0 ; long a = ( 1L * factorial [ n ] * modinverse [ n - r ] ) % mod ; a = ( 1 * a * modinverse [ r ] ) % mod ; return a ; } static void arrange_balls ( int n , int k ) { factorialfun ( ) ; modinversefun ( ) ; for ( int i = 1 ; i <= k ; i ++ ) System . out . print ( ( 1L * binomial ( n - k + 1 , i ) * binomial ( k - 1 , i - 1 ) ) % mod + " ▁ " ) ; } public static void main ( String [ ] args ) { int n = 5 , k = 3 ; arrange_balls ( n , k ) ; } }