(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*.

**See also**
*iteration*, *divide and conquer*, *divide and marriage before conquest*, *recursive*, *recurrence relation*.

*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:**divide**the problem into one or more simpler or smaller parts of the problem,**call**the function (recursively) on each part, and**combine**the solutions of the parts into a solution for the problem.

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.

- Write a function to compute the sum of all numbers from 1 to n.
- Write a function to compute 2 to the power of a non-negative integer.
- Write a function to compute any number to the power of a non-negative integer.
- Write a function to compute the nth
*Fibonacci number*. - Write a function to compute the greatest common divisor (GCD) of two positive integers with
*Euclid's algorithm*. - 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

- Write a function to compute any number to the power of a non-negative integer using
*repeated squaring*, that is, x^{2n}= (x^{n})² and x^{2n+1}= x × x^{2n}. (after "ML for the Working Programmer", pages 45 and 46). - 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).

See dynamic algorithms for an example of one trade-off between speed and clarity for a recursive vs. an iterative implementation. See the notes for *towers of Hanoi*, a puzzle that has another recursive and iterative solution. Bro. David Carlson's tutorial and code (C++) with examples for factorial, Fibonacci, quicksort, and merge sort.

Go to the Dictionary of Algorithms and Data Structures home page.

If you have suggestions, corrections, or comments, please get in touch with Paul Black.

Entry modified 30 September 2013.

HTML page formatted Mon Feb 2 13:10:40 2015.

Cite this as:

Paul E. Black and Patrick Rodgers, "recursion", in
*Dictionary of Algorithms and Data Structures* [online], Vreda Pieterse and Paul E. Black, eds. 30 September 2013. (accessed TODAY)
Available from: http://www.nist.gov/dads/HTML/recursion.html