120 likes | 138 Views
Learn about recursion, its mathematical utility, and its role in computation. Follow Java examples to understand recursive methods and their applications in solving computations effectively.
E N D
Class 3 - Recursion • Recursion • Fundamentals of recursion • Number-theoretic functions
Recursive methods As of now, we lack the ability to do repetitive actions. Can solve them using recursive methods: A recursive method is one that calls itself.
Why study recursion? Not used much in practice, but: • Mathematically useful - related to principle of induction • Used to specify programs (rather than write them). • Represents basic principle of computation. • It is the most general method of repetitive computation.
What basic principle? All computation is, in some sense, performed in one of two ways: • Directly (e.g. addition) • By solving a “simpler” version of the computation and using this solution to get the desired answer.
Recursive methods in Java Recursive method f with argument x has the form static typename f (typename x) { if (x is simple enough) solve directly else use f(value “smaller than” x)to calculate f(x) }
Recursion on integers On integers, this becomes static int f (int x) { if (x is a small enough number) return expression using x; else { int y = f (number less than x); return expression using x and y; } }
Recursion example Given n, calculate sum n+(n-1)+ ... +1 (for n 0) static int sum (int n) { if (n == 0) return 0; else { int y = sum (n-1); return n+y; } }
Computing using sum • The sum method, in mathematical style: S(0) = 0 S(n) = n + S(n-1), if n 0 • Example computation S(3) = 3 + S(2) = 3 + (2 + S(1)) = 3 + (2 + (1 + S(0))) = 3 + 2 + 1 + 0
Java computation for sum • Java computation works the same way: sum(3) sum(2) sum(1) sum(0) 6 3 1 0
Recursion example Define f(i) to be the ith number in the sequence 5, 8, 11, 14, 17, … (counting from zero) static int f (int i) { if (i == 0) return 5; else { int y = f(i-1); return y+3; } }
Recursion on integers Methods returning void can also be defined by recursion. Basic principle: use computation on smaller values to perform computation on larger values.
Recursion example Given n, print numbers n, n-1, ..., 0 static void printnums (int n) { if (n == 0) { System.out.print(0); return; } else { System.out.print(n); printnums(n-1); return; } }