In: Computer Science
using Java
Implement a class called Binomial_Coefficient
o Your class has 2 int attributes, namely K and n
o Create an overloaded constructor to initialize the variables into
any positive integers such that n > k > 0o Create a method
that calculates the value of binomial coefficient, C(n,k) , using
the following rule:
▪ For an array of size (n+1) X (k+1)
▪ Array [n][k] = Array[n-1][ k-1]+ Array[n-1] [k]▪ Array[n][0]=
Array[n][n] = 1
▪ Hence, C(n,k) = array [n][k]
o Create a method that prints the content of your array
➢ Write a main method to test your logic with different
combinations of n & k.
➢ Make sure in your main function tests the the values of n & k
to meet the condition n > k > 0➢ If the user enters wrong
combination prompt the user to reenter valid values of n &
k
For your information:
Binomial coefficients are coefficients of the binomial
formula:
(a + b)n = C(n,0)anb0 + . . . + C(n,k)an-kbk + . . . +
C(n,n)a0bn
Binomial Coefficient are calculated as follow:
C(n,k) = nCk = (nk) = n!/(k! * (n-k)! )
C(n,k) = C(n-1,k) + C(n-1,k-1) for n > k > 0
C(n,0)=1, C(n,n)=1 forn0
Screenshot
Program
import java.util.Scanner;
//Create a binomial class
public class Binomial_Coefficient {
//Instance variables
private int k;
private int n;
//Constructor
public Binomial_Coefficient(int n,int k){
Scanner sc=new
Scanner(System.in);
while(!(n>k && k>0))
{
System.out.println("Enter value of k: ");
k=sc.nextInt();
System.out.println("Enter value of n: ");
n=sc.nextInt();
}
this.k=k;
this.n=n;
}
//Coefficient calculation function
public void calculateCoefficients() {
int coefficientsArray[][]=new
int[n+1][k+1];
for(int i=0; i<=n; i++) {
int min =
i<k? i:k;
for(int j = 0; j
<= min; j++) {
if(j==0 || j == i) {
coefficientsArray[i][j] =
1;
}
else {
coefficientsArray[i][j] =
coefficientsArray[i-1][j-1] + coefficientsArray[i-1][j];
}
}
}
printArray(coefficientsArray,n,k);
}
// Create a method that prints the content of your
array
public void printArray(int[][] arr,int n,int k)
{
System.out.println("Coefficients
Array: ");
for(int i=0;i<n;i++) {
for(int
j=0;j<k;j++) {
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
System.out.println();
}
//Main method
public static void main(String[] args) {
//Create test
Binomial_Coefficient b=new
Binomial_Coefficient(7,3);
b.calculateCoefficients();
}
}
-------------------------------------------------------------------------------
Output
Coefficients Array:
1 0 0
1 1 0
1 2 1
1 3 3
1 4 6
1 5 10
1 6 15