In: Computer Science
Provide a recursive definition of some sequence of numbers or function (e.g. log, exponent, polynomial). Choose one different from that of any posted thus far. Write a recursive method that given n, computes the nth term of that sequence. Also provide an equivalent iterative implementation. How do the two implementations compare?
Implementation for ex
Recursive Solution:
float seriesRecursive(int x, int n) {
if(n == 0)
return 1;
return (((float)x / n) *
seriesRecursive(x, n - 1));
}
Iterative Solution:
float seriesIterative(int x, int n) {
int fact = 1, fx = 1;
for(int i = 1; i < n; i++)
{
fx *= x;
fact *= i;
}
return (float)fx / fact;
}
Comparison:
Every iterative code can be converted into recursive code and vice-versa. Usually recursive code length is less than iterative code (less code). But recursive code has more space complexity than iterative one and that is because recursive code uses stack to call method recursively and hence extra space is needed. However both takes same time complexity usually.