SparkNotes Shopping Cart  |     |  Checkout
Brought to you by Barnes and Noble
Examples of Recursion
  
 
Problems
Problem 4.1: Write a function to recursively print out an integer in any base from base 2 to base 9. [Solution]
Problem 4.2: Write a recursive function int count_digit(int n, int digit); to count the number of digits in a number n (n > 0) that are equal to a specified digit. For example, if the digit we're searching for were 2 and the number we're searching were 220, the answer would be 2. [Solution]
Problem 4.3: For some reason, the computer you're working on doesn't allow you to use the modulo operator % to compute the remainder of a division. Your friend proposes the following function to do it:
int remainder(int num, int den)
{
	if (num < den) return num;
	else return(remainder(num - den, den));
}
Does this function work? Is there a better way? [Solution]
Problem 4.4: The following function iteratively computes xn:
int exponentiate_i(int x, int n)
{
	int i, result = 1;
	for(i=0; i<n; i++) result *= x;
	return result;
}
Write a function to do this recursively in O(n) time). [Solution]
Problem 4.5: Use the knowledge that xn = = (x2)(n/2) when n is even to write a more efficient solution to the above problem. [Solution]
Problem 4.6: The classic fibonacci problem, where the next term in the sequence is the sum of the previous two terms, is often called fib2. One could also imagine a sequence fibN, where N is the number of previous terms to sum up. Write this function recursively. [Solution]
Problem 4.7: What operation does the following function implement when p is 0, 1, and 2?
int mystery(n, m, p)
{
	int i, result = 0;
	
	if (p==0) return n+m;
	for (i=0; i< m; i++) result += mystery(result,n,p-1);
	return result;
}
[Solution]
Help | Feedback | Make a request | Report an error | Send to a friend
 
Feeling hopelessly behind? No Fear Algebra will help you catch up in no time.
More...
 
We'll help you raise your score on the SAT II Physics test!
More...
 
 
Go to top