Question & Answer: C++ programming Just the question about p(2)…..

C++ programming

Just the question about p(2)

(P2) C(n,k) = C(n,n-k)
C(n,k) can be rewritten as n(n-1)(n-2)…(n-k+1)/k!. Implement a program that computes C(n,k) based on this formula, using ints. Hint: the numerator is obviously an iteration, but what is the iteration variable?). Repeat the questions from above. This program is obviously better than 1 since it works on more input values, but how does it compare to 1 efficiency-wise? An appropriate measure of efficiency here would be the number of multiplies.
——-Use property (P2) to make your solution to 3 more efficient (in some cases).
!!!!!!!!!!!!!!!There are better algorithms that require only integer arithmetic, though we do not have enough C knowledge yet to implement these. If you wish to learn more, you can look up dynamic programming algorithms (and arrays to implement them). !!!!!!!!!!!!!!!!!!!

Expert Answer

 

Answer:

#include<iostream>

using namespace std;

long fact(int);//prototype of fact() function

int binomialCoeff(int n,int k) //binomialCoeff() definition starts here

{

int numerator=1,i;

if(n==k) //c(n,n) is 1

return 1;

else if(n==0||n<k) // if n is 0 or n<k, then result is 0

return 0;

else //otherwise

{

for(i=n-k+1;i<=n;i++) // loop starts from (n-k+1) to n

{

numerator=numerator*i;

}

return numerator/fact(k);

}

}

long fact(int n) // function definition of fact()

{

if(n==0||n==1) // if n is 0 or 1 factorial value is 1

return 1;

else

return n*fact(n-1); // recursive call to fact()

}

int main() // main() function definition

{

int n,k,res; //variable declaration

cout<<“Enter the value of n and k in C(n,k):”;//prompts the message

cin>>n>>k;//takes n and k from the keyboard

cout<<“The Value of C(“<<n<<“,”<<k<<“) is “<<binomialCoeff(n,k);; // function call to binomialCoeff() function

return 0;

} //End of main()

Output:

Still stressed from student homework?
Get quality assistance from academic writers!