Starting from:

$35

DS Lab 3 Recursion Solved

 

Lab 3
Recursion

Quang D. C.

In this tutorial, we will approach Recursion thinking. After completing this tutorial, you can apply recursive algorithm to solve some problems.

1. Introduction
A recursive algorithm is an algorithm which calls itself with ”smaller (or simpler)” input values, and which obtains the result for the current input by applying simple operations to the returned value for the smaller (or simpler) input. Generally, if a problem can be solved utilizing solutions to smaller versions of the same problem, and the smaller versions reduce to easily solvable cases, then we can use a recursive algorithm to solve that problem. [1]

Every recursive algorithm involves at least two cases [2]:

•     base case: The simple case; an occurrence that can be answered directly; the case that recursive calls reduce to.

•     recursive case: a more complex occurrence of the problem that cannot be directly answered, but can be described in terms of smaller occurrences of the same problem

recursiveFunction(){ if(simpleCase){

Calculate answers directly

} else{

Call recursiveFunction() on each subproblem

}

}
1

2

3

4

5

6

7

8

In the next section, we will make some recursive function to calculate Factorials and Fibonacci series.

2. Recursive function
2.1. Recursively calculating factorials
The factorial of a non-negative integer number, denoted by n, is defined as follows:



dcquang@it.tdt.edu.vn   1 𝑛! = 𝑛(𝑛 −1)(𝑛 −2)...1 = 𝑛(𝑛− 1)!

In the above formula, the second section defines how-to calculate factorial of n in an iterative version, thus we can use the for statement as follows:

float factorial = 1;

for(i = 2; i <= n; i++)

{

factorial = factorial * i;

}
1

2

3

4

5

From the for statement, we can easily see that each time the statement inside the loop executes, it takes the last factorial result and multiplies it with the new i value, thus we can define the factorial of n as the third part in the formula, that is, 5! = 5 ∗ 4 ∗ 3

∗ 2 ∗ 1 = 5 ∗ 4! = 120. The evaluation of 5! would proceed as in Figure 1, in the left figure, the recursive call executes until 1!, and it returns 1 (the base case) and terminates the recursion. In the left figure, it shows the values returned from each recursive call to its caller until the final value is calculated and returned.

 

Figure 1: Recursive evaluation of 5!

The program below will illustrate how-to program a recursive function.

public class Recursion { public static double computeFactorial(int n)

{

if(n == 0 || n == 1) return 1;

return n * computeFactorial(n - 1);

}

public static void main(String[] args)

{

System.out.println(computeFactorial(5));

}

}
1

2

3

4

5

6

7

8

9

10

11

2.2. Fibonacci series
The Fibonacci series begins with 0 and 1 and has the property that each subsequent Fibonacci number is the sum of the previous two Fibonacci numbers. The Fibonacci series may be defined recursively as follows:

𝑓𝑖𝑏𝑜𝑛𝑎𝑐𝑐𝑖(0) = 0

𝑓𝑖𝑏𝑜𝑛𝑎𝑐𝑐𝑖(1) = 1

𝑓𝑖𝑏𝑜𝑛𝑎𝑐𝑐𝑖(𝑛) = 𝑓𝑖𝑏𝑜𝑛𝑎𝑐𝑐𝑖(𝑛 −1)+ 𝑓𝑖𝑏𝑜𝑛𝑎𝑐𝑐𝑖(𝑛− 2)

From the above formula, calculates the 𝑛𝑡ℎ Fibonacci number recursively using function fibonacci. Notice that Fibonacci numbers tend to become large quickly, so we use data type float for the parameter type and the return type also.

public class Recursion { public static double fibonacci(int n)

{

if(n == 0) return 0; if(n == 1) return 1;

return fibonacci(n - 1) + fibonacci(n - 2);

}

public static void main(String[] args)

{

System.out.println(fibonacci(10)); }

}
1

2

3

4

5

6

7

8

9

10

11

12

Each time the fibonacci function is invoked, it immediately tests for the base case n is equal to 0 or 1. If this is true, n is returned. Interestingly, if n is greater than 1, the recursion step generates two recursive calls, each solves a slightly simpler problem than the original call to fibonacci. Figure 2 shows how the function fibonacci evaluates when n = 3.

 

Figure 2: Evaluating fibonacci(3)

3. Recursion vs. Iteration
We have studied two kinds of functions which implemented in either recursive or iteratively. In this section, we compare the two approaches and discuss why you might choose one approach over the other in a particular situation.

•     Both iteration and recursion are based on a control structure: Iteration uses a repetition structure; recursion uses a selection structure.

•     Both iteration and recursion involve repetition: Iteration explicitly uses a repetition statement; recursion achieves repetition through repeated function calls.

•     Iteration and recursion each involve atermination test: Iteration terminates when the loop-continuation condition fails; recursion when a base case is recognized.

•     Iteration with counter-controlled repetition and recursion each gradually approach termination: Iteration keeps modifying a counter until the counter assumes a value that makes the loop-continuation condition fail; recursion keeps producing simpler versions of the original problem until the base case is reached.

•     Both iteration and recursion can occur infinitely: An infinite loop occurs with iteration if the loop-continuation test never becomes false; infinite recursion occurs if the recursion step does not reduce the problem each time in a manner that converges on the base case.

4. Excercise

Exercise 1
Using iteration, define the functions to:

(a)        Compute factorial of n.

(b)        Compute 𝑥𝑛.

(c)        Count the number of digits of a positive integer number.

(d)        Check an positive integer number is prime or not.

(e)        Find the Greatest Common Divisor (GCD) of 2 positive integer numbers. (Using Euclid algorithm)

Exercise 2
Using recursion, define the functions to:

(a)        Compute factorial of n.

(b)        Compute 𝑥𝑛.

(c)        Count the number of digits of a positive integer number.

(d)        Find the Greatest Common Divisor (GCD) of 2 positive integer numbers. (Using Euclid algorithm)

Exercise 3
Define a recursive function public static boolean checkPrime(int n, int d) that check whether a number is prime (d is current divisor to check)

Exercise 4
Define a recursive function to calculate the following expressions:

(a)        ∑𝑛𝑖=1(2𝑖+1)

(b)        ∑𝑛𝑖=1(𝑖!)

(c)        ∏𝑛𝑖=1(𝑖!)

(d)

                                                     n(n-1)(n-2)⋯(n-r+1),        n = r 0

𝐶(𝑛,𝑘) = {

                                                                                   1,        otherwise

(e)

2𝑛 +𝑛2 +𝑃(𝑛− 1), n 1 𝑃(𝑛) = {

                                                                                     3,     n = 1

Exercise 5
Define a recursive function to convert a Decimal number to Binary. (The output must be an integer number. Example with input is 8, output must be an integer number 1000).

Exercise 6
Using iteration, define the functions to:

(a)            Find and return the minimum element in an array. The array and its size are given as parameters.

(b)            Find and return the minimum element in an array. The array and its size are given as parameters.

(c)            Count how many even numbers are there in an array. The array and its size are given as parameters.

Exercise 7
Using recursion, define the functions to:

(a)            Find and return the minimum element in an array. The array and its size are given as parameters.

(b)            Find and return the minimum element in an array. The array and its size are given as parameters.

(c)            Count how many even numbers are there in an array. The array and its size are given as parameters.

Exercise 8
Using Linked List in Lab 1 for this exercise.

(a)            Implement method addSortedList(E item) to insert new element to a sorted linked list, that means we have to find the first node whose value is bigger than item and insert before it.

(b)            Suppose we have a linked list contains integer numbers, do the following requirements:

•     Count all even numbers.

•     Sum all numbers.

5. Reference
[1]. https://www.cs.odu.edu/ toida/nerzic/content/recursive𝑎𝑙𝑔/𝑟𝑒𝑐𝑎𝑙𝑔.ℎ𝑡𝑚𝑙

[2]. https://web.stanford.edu/class/archive/cs/cs106b/cs106b.1178/lectures/7-IntroToRecursion/7IntroToRecursion.pdf

More products