SLIDE 1
CSE 1030 Yves Lesp´ erance Lecture Notes Week 8 — Recursion
Recommended Readings: Van Breugel & Roumani Ch. 7 and Savitch Ch. 11 and Sec. 12.2
Recursive Methods
Consider the factorial function in maths: 0! = 1 1! = 1 2! = 2 × 1 = 2 3! = 3 × 2 × 1 = 6 4! = 4 × 3 × 2 × 1 = 24 . . . n! = n × (n − 1) × . . . × 1 (*) A simple Java method that uses a loop to compute the function is: public static int factorial(int n) { int prod = 1; for(int i = 1; i <= n; i++) prod = prod * i; return (prod); }
2
In mathematics, it is common to give a recursive definition to such functions: n! =
- 1
if n = 0 n × (n − 1)!
- therwise
Notice that the function is mentioned on the right hand side of the definition! Yet it is not circular; we can use it to find the value of the function for any argument, e.g.: 4! = 4×3! 3! = 3×2! 2! = 2×1! 1! = 1×0! 0! = 1 1! = 1 × 1 = 1 2! = 2 × 1 = 2 3! = 3 × 2 = 6 4! = 4 × 6 = 24
3
In contrast to (*), this definition precisely specifies n! for arbitrarily large n’s. Recursive definitions are also called inductive definitions. This kind of approach is often used in computer algorithms and pro-
- grams. We can write a Java method that computes n! by recursion: