Unit 5 Fun Pro I

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

Unit 5.

Recursion
• Scope

5.1. Introduction
5.2. Principle of mathematical induction
5.3. Elemental recursion
5.3.1. Inductive and base cases
5.3.2. Execution of recursion
5.3.3. Types of recursion

Programming Fundamentals I
Unit 5. Recursion
• Recommende bibliography
- Muñoz Caro C., Niño A. y Vizcaíno Barceló A. Introducción a la
programación con orientación a objetos. Chapter 6. Prentice-
Hall, 2002. Reimpresión 2007

- Introduction to Programming in Java (Princeton University).


Chapter 2. Functions:
http://www.cs.princeton.edu/introcs/20functions/

Programming Fundamentals I
5.1. Introduction
• Recursion is a powerful technique where a method is partially
defined itself.

• Recursion is a technique to solve complex problems consisting


in reducing a problem into subproblems, which keep the
structure of initial problem but are easier to solve.

• An example of problem defined in a recursive way we can find


the search of a word in a dictionary.

• From a formal point of view, the presentation of recursion


should start showing the principle of mathematical induction
on which recursion is based.

Programming Fundamentals I
5.2. Principle of Induction (I)

• The the principle of mathematical induction is a technique


to prove a theorem, normally refered to integer numbers.
The principle needs two steps:

– Check if the theorem is proved with N (inductive


hypothesis) and consequently with N+1.

– Check if the theorem is valied for the fist possible value.


If this fact is true, due to the first step, the theorem must
be valid for the second value and so on, this fact
completes the demonstration.

Programming Fundamentals I
5.2. Principle of Induction (II)
• Example: Let the following theorem be:
For each integer N≥1, the addition of the first N integers given by:
N

å i =1 + 2 + 3 + ... + N
i =1

is equal to N(N+1)/2.

• Demonstration
a) Inductive hypothesis. We demonstrate that if the theorem is valid
for N then is valid for N+1:
N +1 N

å i = å i + ( N + 1 ) = N ( N + 1 ) / 2 + ( N + 1 ) = ( N + 1 )( N + 2 ) / 2
i =1 i =1

 Q. E. D.

Programming Fundamentals I
5.2. Principle of Induction (III)
• Demonstration
b) Check if the theorem is valid for the first value, N=1:
1
We have:
å i =1
i =1

1
with the formula:
å i = N ( N + 1 ) / 2 = 1( 1 + 1 ) / 2 = 1
i =1
is valid for 1 and, therefore, for 2 y, therefore, for 3 and so on …

• As we have seen, a proof by induction involves two steps. In a step it


is demonstrated that the the theorem is valid for the simplest case,
this is the base case. On the other hand, it is necessary to
demonstrate that if the the theorem is valid for a case, it is possible to
extend it for the following case, this is indictive case. Recursion
works in an analogous way.

Programming Fundamentals I
5.3. Elemental recursion
• In programming recursion is implemented as a method which
calls itself.

• The method has to detect the two cases of the principle.

• That is, recursion is a simulation of the induction theorem.

• Next we will describe it in detail.

Programming Fundamentals I
5.3.1. Base and Inductive Cases (I)
• Recursion is related to the principle of induction. There exists a
base case, where inductive calls are not executed. On the hand,
there exists an inductive case (also called recursive or general
case), where different versions of the method are called. These
versions receive simpler parameters which address to the base
case. Hence, in a recursive method:

– It is necessary to include at least a base case (more than


one if needed) which does include a recursive call. The
method has to check if a recursive call is necessary or the
base case is reached.

– Every recursive call has to address to the base case where


all recursive calls have to end. If the base case is not
reached then we have a problem: infinite recursion.

Programming Fundamentals I
5.3.1. Base and Inductive Cases (II)
• To create a recursive method is necessary a recursive
definition of the problem.

• Example: Let see the problem of the addition of the first n


integers with n≥1.
n

åi
i =1

• Let s(n) denote the addition of n integers, so:


– Base case: s(1)=1
– Inductive case : s(n)=s(n-1)+n

• Program:

Programming Fundamentals I
5.3.1. Base and Inductive Cases (III)
import java.util.*;
class Recursion {
public static void main(String [] args) {
int n, sum;
Scanner leer =new Scanner(System.in);

n=leer.nextInt ();

if (n>0) {
sum= s(n);
System.out.println(“Addition of the first "+n+" integers:“+ sum);
}
else {
System.out.println(“The number cannot be < 1");
}

} // End main

Programming Fundamentals I
5.3.1. Base and Inductive Cases (IV)
public static int s(int n) {
int value;
if (n==1) // base case
value = 1;
else
value = s(n-1)+n; // inductive case
return value;
}
}

Programming Fundamentals I
5.3.2. Execution of recursion (I)
• How does recursion work? Let’s see an example

• Example: Recursive factorial


N
N != Õ i
i =1

– Indictuve case: N! = N * (N-1)!


– Base case : 0! = 1

Programming Fundamentals I
5.3.2. Execution of recursion (II)
• Program:

import java.util.*;
class RecursiveFactorial{
public static void main(String [ ] args) {
int n;
System.out.println(“Computing recursive factorial\n");
Scanner leer =new Scanner(System.in);
n=leer.nextInt ();

if (n >=0) {
System.out.println(“The factorial of "+n +" is:");
System.out.println(factorial(n));
}
else
System.out.println(“It cannot be computed if n<0");
} // End main

Programming Fundamentals I
5.3.2. Execution of recursion (III)
public static long factorial(int n) {
long nFact;
if (n==0){
nFact = 1; Base case
}
else{
nFact = factorial(n-1)*n; Inductive case
}
return nFact;

} //End class

• Let analyse what happens when n=3

Programming Fundamentals I
5.3.2. Execution of recursion (IV)
main public static long factorial(int n) {
long nFact;
n=3 if (n==0){
nFact = 1;
Returns 2*3=6 }
factorial else{
nFact = factorial(n-1)*n;
n=2 }
return nFact;
factorial Returns 1*2=2
}
n=1

factorial Retuns 1*1=1

n=0

factorial ¡ Base case! Returns 1

Programming Fundamentals I
5.3.2. Execution of recursion (V)
• En forma de tabla

Forward Backward

Call n Value
1ª 3 6 Result
2ª 2 2
3ª 1 1
4ª Base case 0 1

Programming Fundamentals I
5.3.2. Execution of recursion (VI)
• General expression of a recursive algorithm:

Begin
Receive the value of the variable

If (value is the lowest) then There exists


base case always
else conditional
structure to
call method with a value lower than the original distinguish the
End_if cases

Return result
End

Programming Fundamentals I
5.3.2. Execution of recursion (VII)

• VERY Important:

- The principal of mathematical induction ENSURES that if


the inductive and bases cases are correctly designed for
my problem then the recursive algorithm NECESSARILY
returns the correct result.

• Iteration and recursion present several resemblances

Programming Fundamentals I
5.3.2. Execution of recursion (VIII)
• Comparision between recursion and iteration:

– Analogies:
• Both involve repetition.

• Both need a way of finishing.

• Both construct gradually the solution.

• Both can continue “infinitely”.

Programming Fundamentals I
5.3.2. Execution of recursion (IX)
• Comparision between recursion and iteration:
– Differences:
• Recursion has a disadvantage: the method is being
constantly called. This fact involves an extra cost in terms of
computational time and memory, because new variables are
defined for each invokation. The difference in terms of
efficiency depends on how grows the stack of data in the
recursive case.

• Every problems solved by a recursive approach can be


solver by an iterative approach as well. But if this fact is true,
why to use recursion? Recursion is chosen when the
recursive solutions represents a more natural solution and
the final program is easier to understand and debug and not
excessively more inefficient.

Aplications: design of algorithm such as Divide and conquer (The Hanoi


Towers); Backtracking (Labyrinth); Dynamic Programming (typical
example Fibonacci)

Programming Fundamentals I
5.3.3. Types of recursion (I)
• The most simple classification is:

– Direct recursion. A method calls itself. This is the case


shown in the previous examples.

– Indirect recursion. The original method is called after calling


other methods.

Programming Fundamentals I
5.3.3. Types of recursion (II)
• Illustration of indirect recursion:

ida
método 1 método 2 Llamada recursiva
vuelta
ida vuelta
ida
método 1 método 2 Llamada recursiva
vuelta
ida vuelta
ida
método 1 método 2 Caso
base
vuelta

¡Indirect recursion should be avoid becuase it involves


many problems!
Programming Fundamentals I

You might also like