The mathematical operation “n choose r” denotes all ways of choosing r elements from a set of n elements. For example:
ExpressionResultExplanation4 choose 41there is 1 way of choosing 4 items from a set of 4 (take them all!)4 choose 14there are 4 ways of choosing 1 item from a set of 4 (pick one!)4 choose 26there are 6 ways to choose 2 – try it4 choose 34there are 4 ways to choose 3 – try it3 choose 40can’t take 4 items from a set of 3
Write a recursive function called choose which takes as input two integers, n and r, and returns the number of possible ways of choosing.
Hints:
To choose 3 marbles from a collection of 5, decide if the first marble is “in” (part of the chosen set) or “out”. If it is “in” then recursively choose 2 more from a collection of 4. If it is “out” then recursively choose 3 from a collection of 4. Combine these two scenarios to form the recursive case.Consider the possible base cases - there are more than one!
Declare and implement a recursive function to display a decimal integer (i.e. base 10) in binary notation. It should have the following signature in recursion.h:
void show_as_binary (int n);
The iterative solution to this function might be something like:
void show_as_binary (int n) { int bit = 0; string bin = ""; while (n > 0) { bit = n % 2; n /= 2; bin = to_string(bit) + bin; } cout << bin; }
However, the recursive solution does not need a string accumulator - you can cout the bits directly.