So, I have implemented the binomial coefficient
public static int binomial(int n, int k) {
if (k == 0)
return 1;
else if (k > n - k)
return binomial(n, n - k);
else
return binomial(n - 1, k - 1) * n / k;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Insert n: ");
int n = scan.nextInt();
System.out.println("Insert k: ");
int k = scan.nextInt();
System.out.println("Result: " + binomial(n, k));
}
And it works, but where I'm stuck is just that I need to add the coefficient array for two given numbers. So If n
is 5
and k
is 3
. The coefficient array will display: 1 5 10 10
. Any ideas?
All you need to do is put your expression in a loop and hold n
constant.
for (int k = 0; k <= n; k++) {
System.out.print(binomial(n, k) + " ");
}
You can store these values in an array if you like. There is no need to make your method any more complicated.
If want to put it in an array, here is one easy way to do it.
int coefs[] = IntStream.rangeClosed(0, n).map(k -> binomial(n, k)).toArray();
coefs[] = [1, 5, 10, 10, 5, 1]