Monday, 17 August 2015

Minimal Combinatorial

Standard
Given two integers - n and r, your task is to calculate the combinatorial nCr.
nCr = n! / r! (n-r)!
The caveat is that you have to write code to do this calculation in minimum number of characters.

UPDATE: The testcases for this problem have been fixed. Please try submitting your solution again.

Input
The first line will be number of testcases T. Then T lines follow, each containing two positive integers - n and r.

output
Print T lines, each line containing the value of nCr.

Constraints
1 <= T <= 100
1 <= r <= n <= 1000

You can assume that the value nCr will fit into a signed 64 bit integer.

Scoring
If your program passes all the testcases, the score will be assigned according to the following formula:
num_chars = length of source code
Score = (1000 - num_chars) / 10


You can understand that you have to reach as close to 100 as possible. Have fun :)

Sample Input
1
100 10
Sample Output
17310309456440

Time Limit: 2 sec(s) for all input files combined.
Memory Limit: 256 MB
Source Limit: 1024 KB 
 
Code: 
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
class TestClass{
 
public static BigInteger fact(int n){
if(n==1) return BigInteger.valueOf(n);
 
 else return BigInteger.valueOf(n).multiply(fact(n-1));
}
public static void main(String args[]) throws Exception{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int c=Integer.parseInt(br.readLine());
for(int i=0;i<c;i++){
String[] p=br.readLine().split(" ");
int n=Integer.parseInt(p[0]),
r=Integer.parseInt(p[1]);
System.out.println(fact(n).divide(fact(r).multiply(fact(n-r))));
}
}

0 comments:

Post a Comment