I have midterm exams coming up next week and I've come upon a problem that I just can't crack (I find recursion so confusing!). I need to convert this recursive function into an iterative one, I appreciate any help/hints, etc!
The recursive solution:
long F(int n) {
if (n >= 0) {
if (n >= 3) {
//std::cout << "Current n is: " << n << std::endl;
long result = 0;
result = 3 * F(n - 1) + 2 * F(n - 2) + F(n - 3);
//std::cout << "Current result is : " << result << std::endl;
return result;
}
else {
return n;
}
}
else {
return -1;
}
}
My attempt at a iterative solution:
long F2(int n) {
if (n >= 0) {
long outterResult = 0;
long innerResult = 0;
for (int o = n; o >= 3; o--) {
outterResult += innerResult;
int iteration = 1;
for (int i = 3; i > 0; i--) {
innerResult += i*(n-iteration);
iteration++;
}
//std::cout << "Current n is: " << n << std::endl;
//std::cout << "Current result: " << outterResult << std::endl;
}
return outterResult;
}
else {
return -1;
}
}
Cheers!