Skip to content

Instantly share code, notes, and snippets.

@ikbear
Created March 10, 2011 12:16
Show Gist options
  • Save ikbear/864015 to your computer and use it in GitHub Desktop.
Save ikbear/864015 to your computer and use it in GitHub Desktop.
Computing Combinations with Java
import java.math.*;
public class cnk{
public static BigInteger cnk(int n, int k)
{
BigInteger fenzi = new BigInteger("1");
BigInteger fenmu = new BigInteger("1");
for(int i=n-k+1; i <= n; i++){
String s = Integer.toString(i);
BigInteger stobig = new BigInteger(s);
fenzi = fenzi.multiply(stobig);
}
for(int j=1; j <= k; j++){
String ss = Integer.toString(j);
BigInteger stobig2 = new BigInteger(ss);
fenmu = fenmu.multiply(stobig2);
}
BigInteger result = fenzi.divide(fenmu);
return result;
}
public static void main(String args[])
{
int n = 100, k = 2;
BigInteger result = cnk(n, k);
System.out.println(result.toString());
}
}
@KruthikaS
Copy link

if i give n=32145 and k=12345 ( ie 5 digit input) it is not working

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment