Last active
November 24, 2020 17:57
-
-
Save jarekt/0f21286c376ce8eaa140bd15a4c5b7bf to your computer and use it in GitHub Desktop.
binomic coefficient calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.math.BigInteger; | |
/** | |
* KombinacniCislo | |
*/ | |
public class KombinacniCislo | |
{ | |
public static void main(String[] args) | |
{ | |
int n = 0; | |
int k = 0; | |
try | |
{ | |
n = Integer.parseInt(args[0]); | |
k = Integer.parseInt(args[1]); | |
} | |
catch (Exception e) | |
{ | |
System.out.println("expected two int arguments"); | |
System.exit(1); | |
} | |
int spaces = Math.abs(n) > Math.abs(k) ? Integer.toString(n).length() : Integer.toString(k).length(); | |
BigInteger out = binomialCoeff(n, k); | |
System.out.printf("/ %s \\\n", indentString(Integer.toString(n), spaces)); | |
System.out.printf("| %s | = %s\n", indentString( "", spaces), out.signum() != 1 || n < 0 || k < 0 ? "Math error" : out); | |
System.out.printf("\\ %s /\n", indentString(Integer.toString(k), spaces)); | |
} | |
static String indentString(String a, int lenght) | |
{ | |
for (int i = a.length(); i <= lenght; i++) | |
{ | |
a = " " + a; | |
} | |
return a; | |
} | |
static BigInteger binomialCoeff(int n, int k)//could take biginteger as input as well, not necesary tho as it should not overflow | |
{ | |
if (k == 1) | |
{ | |
return BigInteger.valueOf(n); | |
} | |
else if (k == 0) | |
{ | |
return new BigInteger("1"); | |
} | |
else if (n < k) | |
{ | |
return new BigInteger("-1");//math error | |
} | |
else | |
{ | |
int n_limit, k_limit;//slight simplification of the algebraic formula | |
BigInteger n_out = new BigInteger("1"); | |
BigInteger k_out = new BigInteger("1"); | |
if (k > n - k) | |
{ | |
n_limit = k; | |
k_limit = n - k; | |
} | |
else | |
{ | |
n_limit = n-k; | |
k_limit = k; | |
} | |
for (int i = 0; n - i > n_limit; i++) | |
{ | |
n_out = n_out.multiply(BigInteger.valueOf(n -i)); | |
} | |
for (int i = 0; k_limit - i > 1; i++) | |
{ | |
k_out = k_out.multiply(BigInteger.valueOf(k_limit - i)); | |
} | |
return n_out.divide(k_out); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment