(in c++, do not use #include <iostream.h> or <stdio.h> The formula for computing
ID: 3676165 • Letter: #
Question
(in c++, do not use #include <iostream.h> or <stdio.h>
The formula for computing the number of ways of choosing r different things from a set of n things is the following:
C(n, r) = n! / (r! * (n – r)!)
The factorial function n! is defined by n! = n * (n – 1) * (n – 2) * ... * 1
Discover a recursive version of this formula and write a recursive function that computes the value of the formula. Using this recursive function, write a function which computes the formula for number of ways to choose r different things from a set of n things.
Then write a program that takes r and n as user input, then calls the above functions and outputs the result.
Hint: some of the intermediate values (such as 16!) are too large to fit in a variable of int type. Consider using a type which can store larger numbers such as long (or even unsigned long, since our numbers are all positive in this problem).
The program should print a string of text to the terminal before getting each line of input from the user. A session should look like the following example (including whitespace and formatting), with possibly different numbers in the output:
The strings printed by the program should include a newline at the end, but no other trailing whitespace (whitespace at the end of the line). Also take care of singular and plural words in the sentence (1 way, 2 things etc.)
Explanation / Answer
Solution of the program.
#include <iostream.h>
#include<conio.h>
int factorial(int);
void main(void) {
int r,n,nminusr;
unsigned int result;
cout << "Enter r (number of things to choose) ";
cin >>r;
cout << "Enter n (number of things to choose from) ";
cin >>n;
nminusr=n-r;
result=(factorial(n)/(factorial(r)*factorial(nminusr)));
cout<<"There are"<<result<<"ways to choose"<<r<<"things from a set of"<<n<<"things"<<endl;
}
int factorial(int number) {
int temp;
if(number <= 1) return 1;
temp = number * factorial(number - 1);
return temp;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.