Marbles | CodeChef Solution

Hello coders, today we are going to solve Marbles CodeChef Solution whose Problem Code is MARBLES.

Marbles

Task

Rohit dreams he is in a shop with an infinite amount of marbles. He is allowed to select n marbles. There are marbles of k different colors. From each color there are also infinitely many marbles. Rohit wants to have at least one marble of each color, but still there are a lot of possibilities for his selection. In his effort to make a decision he wakes up. Now he asks you how many possibilities for his selection he would have had. Assume that marbles of equal color can’t be distinguished, and the order of the marbles is irrelevant.

Input Format

The first line of input contains a number T <= 100 that indicates the number of test cases to follow. Each test case consists of one line containing n and k, where n is the number of marbles Rohit selects and k is the number of different colors of the marbles. You can assume that 1<=k<=n<=1000000.

Output Format

For each test case print the number of possibilities that Rohit would have had. You can assume that this number fits into a signed 64 bit integer.

Example

Sample Input

2
10 10
30 7

Sample Output

1
475020

Solution – Marbles

C++

#include <bits/stdc++.h>
using namespace std;
#define ll long long
ll c(ll n,ll r){
    ll res=1;
    if (r>n/2){
     r=n-r;
    }

 for(int i=0;i<r;i++){
 res*=n;
 res/=i+1;
 n--;
 }
 return res;
}
int main() {
    int t;
    cin>>t;
    while(t--){
    int n,k;
    cin>>n>>k;
    cout<<c(n-1,n-k)<<endl;
    }
    return 0;
}
    
    

Python

T=int(input())
for i in range(0,T):
	n,k=map(int,input().split())
	ans=1
	for j in range(1,k):
		ans*=n-k+j
		ans//=j
	print(int(ans))

Java

/* package codechef; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
	public static void main (String[] args) throws java.lang.Exception
	{
		// your code goes here
		Scanner sc = new Scanner(System.in);
		int t = sc.nextInt();
		while(t-- != 0){
		    long n = sc.nextLong();
		    long k = sc.nextLong();
		    
		   
		    if(n==k){
		        System.out.println(1);continue;
		    }
		    n = n-k;
		    long ans = 1;
		   for(int i=1;i<k;i++)
		   {
		       ans=ans*(n+i)/i;
		   }
		   System.out.println(ans);
	}
}
}

Disclaimer: The above Problem (Marbles) is generated by CodeChef but the Solution is Provided by CodingBroz. This tutorial is only for Educational and Learning Purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *