recursion

(algorithmic technique)

Definition: An algorithmic technique where a function, in order to accomplish a task, calls itself with some part of the task.

Specialization (... is a kind of me.)
tail recursion, collective recursion.

Note: Every recursive solution involves two major parts or cases, the second part having three components.

• base case(s), in which the problem is simple enough to be solved directly, and
• recursive case(s). A recursive case has three components:
1. divide the problem into one or more simpler or smaller parts of the problem,
2. call the function (recursively) on each part, and
3. combine the solutions of the parts into a solution for the problem.
Depending on the problem, any of these may be trivial or complex.

Here are some exercises to help you learn recursion. Although recursion may not be the best way to write some of these functions, it is good practice.

1. Write a function to compute the sum of all numbers from 1 to n.
2. Write a function to compute 2 to the power of a non-negative integer.
3. Write a function to compute any number to the power of a non-negative integer.
4. Write a function to compute the nth Fibonacci number.
5. Write a function to compute the greatest common divisor (GCD) of two positive integers with Euclid's algorithm.
6. Write a function to compute GCD based on the following relations
• GCD(2m, 2n) = 2 * GCD(m, n)
• GCD(2m, 2n+1) = GCD(m, 2n+1)
• GCD(2m+1, 2n+1) = GCD(n-m, 2m+1) if m < n
• GCD(m, m) = m
(after "ML for the Working Programmer", page 49).
7. Write a function to compute any number to the power of a non-negative integer using repeated squaring, that is, x2n = (xn)² and x2n+1 = x × x2n. (after "ML for the Working Programmer", pages 45 and 46).
8. Write a function to compute the integer square root of a non-negative integer using square_root(4x) = 2*square_root(x). (after "ML for the Working Programmer", pages 48 and 49).

Authors: PEB,PR