Question: Write one Java program that, in three different ways, calculates the binomial coefficients ? ? ? ? ? ? ? ? k n or C(n,k).

Write one Java program that, in three different ways, calculates the binomial coefficients ? ? ? ? ? ? ? ? k n or C(n,k). Note that ? ? ? ? ? ? ? ? k n is definied for any n ? k ? 0 , otherwise ? ? ? ? ? ? ? ? k n =0. Specific requirements: 1. Part (a): Use a loop to compute ? ? ? ? ? ? ? ? k n = n!/(k!(n-k)!). 2. In Part (b), use pure recursion to compute. Here is a recursive formula ? ? ? ? ? ? ? ? ? ? +? ? ? ? ? ? ? ? ? =? ? ? ? ? ? ? ? 1 1 1 k n k n k n with boundary values 1 0 =? ? ? ? ? ? ? ?n and = 1 ? ? ? ? ? ? ? ? n n . You should count how many times recursive calls are made. 3. Part (c) is considered to be an improved version of Part (b). You may use an array (2-dimessional) to store some values that has already been computed using recursion so that when making recursive calls the program does not compute certain values over and over again. 4. Prompt user to enter two integers as n and k. Report the values of ? ? ? ? ? ? ? ? k n together with the number of recursive calls in each way. Here is a sample output: Enter two integers as n and k to compute C(n,k): 10 5 (a) use a loop: C(10,5)=252. (b) use prue recursion: C(10,5)=252. The number of calls is 502. (c) use recursion with some stored values: C(10,5)=252. The number of calls is 50.

Here is the program I have but it is not compiling correctly:

import java.util.Scanner; class Main{ static int ncr(int n, int r){ int ans=1; for(int i=1;i<=r;i++){ ans = ans*(n-i+1); ans = ans/i; } return ans; } static int rec(int n, int r){ // System.out.println(n+" "+r);  if(nreturn 0; if(r==0){ return 1; } return rec(n-1,r-1)+rec(n-1,r); } static int dp[][],calls=0; static int recdp(int n, int r){ // calls++;  if(nreturn 0; // calls++;  if(r==0)return 1; calls++; if(dp[n][r]!=0)return dp[n][r]; dp[n][r] = recdp(n-1,r-1)+recdp(n-1,r); return dp[n][r]; } public static void main(String[] args) { System.out.println("Enter n and k"); Scanner obj = new Scanner(System.in); int n = obj.nextInt(); int k = obj.nextInt(); System.out.println("Using loop : "+ncr(n,k)); System.out.println("True recursion : "+rec(n,k)); dp = new int[n+1][k+1]; calls=0; System.out.println("Recursion with stored values "+recdp(n,k)+" The number of calls is "+calls); } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!