Docsity

Understanding Recursion: Examples, Nature, and Applications, Study notes of Computer Science

Toggle sidebar
bg1
Introduction
Recursion is a function invoking itself, either directly or indirectly.
Many algorithms and mathematical properties are naturally
expressed in a recursive manner.
It can be used as an alternative to iteration.
Recursion is an important and powerful tool in problem solving and
programming. It is a programming technique that naturally
implements the divide-and-conquer problem solving methodology.
Some programming languages are inherently recursive (Lisp,
Scheme).
In its simplest form the idea of recursion is straightforward:
Example 1: Simple countdown timer
Recursion - 1
Recursion
void count_down(int n)
{
if (n <= 0)
printf(“\nBlast off.\n”);
else{
printf(“%d! “, n);
count_down(n-1);
}
}
int main ()
{
count_down(10);
}
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14

Partial preview of the text

Download Understanding Recursion: Examples, Nature, and Applications and more Study notes Computer Science in PDF only on Docsity!

Introduction  Recursion is a function invoking itself, either directly or indirectly.  Many algorithms and mathematical properties are naturally expressed in a recursive manner.  It can be used as an alternative to iteration.  Recursion is an important and powerful tool in problem solving and programming. It is a programming technique that naturally implements the divide-and-conquer problem solving methodology.  Some programming languages are inherently recursive (Lisp, Scheme). In its simplest form the idea of recursion is straightforward: Example 1: Simple countdown timer

Recursion

void count_down(int n)

if (n <= 0)

printf(“\nBlast off.\n”);

else{

printf(“%d! “, n);

count_down(n-1);

int main ()

count_down(10);

Example 2: Multiplication of natural numbers. a * b = a added to itself b times. (iterative definition) a * b = a if b= (recursive definition) _a b = a * (b-1) + a_* if b > 1 e.g.  6 * 3 = 6 * 2 + 6 = 6 * 1 + 6 + 6 = 6 + 6 + 6 = 18 Example 3: Factorial Function

n! = n * (n-1) * (n-2) * … * 2 * 1

int multiply(int a, int b)

if (b == 1) /* stopping case */

return a;

else /* recursive step

return ( a + multiply(a, b-1));

The Nature of Recursion  One or more simple cases of the problem (called the stopping cases ) have a simple non-recursive solution.  The other cases of the problem can be reduced ( using recursion ) to problems that are closer to stopping cases.  Eventually the problem can be reduced to stopping cases only, which are relatively easy to solve. In general: if (stopping case) solve it else reduce the problem using recursion Tracing a Recursive Function Computer uses a stack to keep track of function calls. Whenever a new function is called, all its parameters and local variables are pushed onto the stack along with the memory address of the calling statement (this gives the computer the return point after execution of the function).

Example 1: Tracing the function multiply

x = multiply(6,3):

a = 6

b = 3

3 <= 1? false

return (6 + multiply(6,2))

a = 6

b = 2

2 <= 1? false

return(6 + multiply(6,1))

a = 6

b = 1

1 <= 1? true

return(6)

Example 3: Trace of palindrome: for input abc

palindrome(3);

n=

3 <= 1? false

read next : a

palindrome(2)

write a

return

n=

2 <= 1? false

read next : b

palindrome(1)

write b

return

n=

1 <= 1? true

read next : c

write c

return

Example 4: Fibonacci Sequence Fibonacci numbers are named in honor of Leonardo Pisano (Leonardo of Pisa), the son of Bonaccio, (which in Latin is Filius Bonaccii) who discovered the series in 1202. The original problem that Fibonacci investigated (in the year 1202) was about how fast rabbits could breed in ideal circumstances. Suppose a newly-born pair of rabbits, one male, one female, are put in a field. Rabbits are able to mate at the age of one month so that at the end of its second month a female can produce another pair of rabbits. Suppose that our rabbits never die and that the female always produces one new pair (one male, one female) every month from the second month on. The puzzle that Fibonacci posed was...How many pairs will there be in one year? (answer appears on last page of the notes)

  1. At the end of the first month, they mate, but there is still one only 1 pair.
  2. At the end of the second month the female produces a new pair, so now there are 2 pairs of rabbits in the field.
  3. At the end of the third month, the original female produces a second pair, making 3 pairs in all in the field.
  4. At the end of the fourth month, the original female has produced yet another new pair, the female born two months ago produces her first pair also, making 5 pairs.
  5. What is the answer to this problem? [see the last page for the answer – but try to figure it out by yourself first!] Fibonacci numbers appear in many unexpected areas. For example, on many plants, the number of petals is a Fibonacci number: buttercups have 5 petals; lilies and iris have 3 petals; some delphiniums have 8; corn marigolds have 13 petals; some asters have 21 whereas daisies can be found with 34, 55 or even 89 petals, all Fibonacci numbers. Look at your own hand: You have ... 2 hands each of which has 5 fingers, each of which has 3 parts separated by 2 knuckles. It is the sequence of integers: t 0 t 1 t 2 t 3 t 4 t 5 t 6 t 7 t 8 t 9 0 1 1 2 3 5 8 13 21 34 …

Proof by Induction Induction proofs are most often used to establish theorems that hold for positive integers. That is, you can establish the validity of a conjecture such as: n  0, and n  integer numbers, it is true that (^)  

n i 0 i 2 n( n 1 ) by showing that the conjecture is true for one or more base values of n (generally, n = 0 is sufficient – though not always). Once this base case is proven true, you assume that the conjecture is true for all values of n from the base case through m , where m is an arbitrary integer greater than or equal to the largest value of n covered in the base case; this is the inductive hypothesis. Finally, using the assumption of the inductive hypothesis you prove that the conjecture is true for the next value of n (i.e., m + 1). This final step is the induction step. To summarize: An induction proof consists of three parts:

  1. Induction base : Show by example that the conjecture is true for one or more values of n. Typically n = 0 is used.
  2. Induction Hypothesis : Assume the conjecture is true for all values of n between the base case value and some arbitrary integer m.
  3. Induction Step : Prove that the conjecture is true (or possibly not true) when n = m +1. Example : Prove by induction the conjecture from above. Conjecture: n  0, and n  integer numbers, it is true that (^)  

n i 1 i 2 n( n 1 ) Basis : n=1, by definition (^)  

n i 1 i (^)  

1 i 1 i (^) 1, by substitution    1 i 1 i 2 1 ( 1  1 ) = 2 2 = 1 So the base case is true!

Inductive Hypothesis : n=k, assume    n i 1 i 2 k( k 1 ) is true. Inductive Step : prove conjecture is true for n = k+ Must prove that:     k 1 i 1 i 2 (k  1 )[(k 1 ) 1 ] = 2 (k  1 )(k 2 ) Note that     k 1 i 1 i (^)   k i 1 i (^) + (k +1) = 2 k( k 1 )

  • (k + 1) Rewriting gives: 2 k^2  k
  • k + 1 = 2 k^2

2 k

2 2 k

2 2 2 k^2

2 k

2 2 k

2 2 = 2 k^2  3 k 2 = 2 (k  1 )(k 2 ) Thus the proof is completed and our conjecture is true for all integer numbers. At first glance, a proof by induction appears to be a circular proof, in that you establish a result by assuming that it is correct. However, an induction proof is not a circular proof for the same reason that a recursive definition is not circular. A correct proof by induction has an induction base that is similar to the base case of a recursive definition. The induction step proves the correctness using the correctness for smaller values of n. Repeated application of the induction step reduces the proof to one that is solely in terms of the base. Common Errors with Recursion

Problem Solving with Recursion The Towers of Hanoi Problem : involves moving a specified number of disks (N) that are all different sizes from one tower to another. The goal is to move all disks from tower A to C subject to the following rules:

  1. Only one disk may be moved at a time and this disk must be the top disk on a tower.
  2. A larger disk can never be placed on top of a smaller disk. The stopping cases of the problem involve moving only one disk.

Towers of Hanoi: Solution

Test: tower(3,‘A’,’C’, ’B’); Output: Move from A to C Move from A to B Move from C to B Move from A to C Move from B to A Move from B to C Move from A to C Practice Problems

  1. Trace the following recursive function:

#include <stdio.h>

int f(char *s)

if (*s == '\0')

return 0;

else

return (1 + f(s+1));

int main()

char a[20] = "Computer Science I";

printf("%d\n",f(a));

  1. Trace the following recursive function:

#include <stdio.h>

int f(int c)

if (!(c > 10)) {

printf("%d\n", c);

f(c + 1);

int main()

f(0);

  1. Write a recursive function to check if a given item is a member of a set. Function prototype is:
  2. Write a recursive function to check if the contents of an array are in ascending order or not. The function prototype is:

/* Inputs: An integer array, the item

being searched and the index of the

last element in the array.

Output: true (1) or false (0)

int isMember(int a[], int item, int n);

/* Inputs: an integer array, the index

of the last element in the array.

Output: true or false.

int isAscending(int a[], int n);

Answer to Fibonacci’s Rabbit Puzzle

  1. At the end of the first month, they mate, but there is still one only 1 pair. Total is 1 pair. Call them M1/F1.
  2. At the start of the second month there is 1 pair. At the end of the second month the female F1 produces her first new pair (call them M2/F2 like before), so now there are 2 pairs of rabbits in the field. Total is 2 pairs. M1/F1, M2/F
  3. At the start of the third month there are 2 pairs [M1/F1, M2/F2]. At the end of the third month, the original female (F1) produces her second pair, making 3 pairs in the field. Total is 3 pairs. M1/F1, M2/F2, M3/F
  4. At the start of the fourth month there are 3 pairs. Two pairs will reproduce, one pair is not yet mature. Three pairs at start of month plus two pairs produced this month totals 5 pairs.
  5. At the start of the fifth month there are 5 pairs. Three pairs will reproduce, two pairs are not yet mature. At the end of the fifth month, the original female (F1) produces her fourth new pair, the female born three months ago (F2) produces her second pair, and the female born two months ago (F3) produces her first pair. [5 pairs at start + 3 pairs produced] Total is 8 pairs. The table below illustrates the complete process more succinctly. A B C D E F month total pairs at start of month number of mature pairs at start of month number of immature pairs number of pairs produced by mature pairs total number of pairs at end of month (sum of columns B and E) 1 1 0 1 0 1 2 1 1 0 1 2 3 2 1 1 1 3 4 3 2 1 2 5 5 5 3 2 3 8 6 8 5 3 5 13 7 13 8 5 8 21 8 21 13 8 13 34 9 34 21 13 21 55 10 55 34 21 34 89 11 89 55 34 55 144 12 144 89 55 89 233