In: Computer Science
Need a description what does this program does and how does it work.
#include <iostream>
using namespace std;
double function(int num, double* memorize);
int main()
{
int num=5;
char cont;
double* memorize = new double[num + 1];
do {
cout << "Enter n ";
cin >> num;
memorize[1] = 1;
memorize[2] = 1;
memorize[3] = 1;
memorize[4] = 3;
memorize[5] = 5;
for (int i = 6; i <= num; i++)
memorize[i] = -1; // -1 means that the value is not in the array
cout << num << "th number: " << function(num, memorize) << endl;
cout << "Continue?";
cin >> cont;
cout << endl;
} while (cont == 'y' || cont == 'Y');
delete[] memorize;
return 0;
}
double function(int num, double* memorize)
{
// checks if value was calculated before
if (memorize[num] == -1)
{
// recursively calculates said value and stores it in
memorize[num] = function(num - 1, memorize) + (3 * function(num - 5, memorize));
}
return memorize[num];
}
This question basically solves a equation which is below:
T(N) = T(N-1) + 3 * T(N-5)
with base conditions as:
T(N) = 1 for 1 <= N <= 3
T(N) = 3 for N=4
T(N) = 5 for N=5
================================================
This code basically sees that to solve the above problem using
recursion, we would get overlapping subproblems, which will be
unnecessary work..
So like if we need to solve T(10), then:
T(10) = T(9) + 3 * T(5)
T(9) will be broken as T(8) + 3*T(4)..
T(8) will be broken as T(7) + 3*T(3)..
T(7) will be broken as T(6) + 3*T(2)..
T(6) will be broken as T(5) + 3*T(1)..
So we again, got to solve T(5), which we already did in the above
bolded part.. Hence it is repeated subproblem.. So To avoid this
problem, we just memorize the values which we solve.. using the
memorize double array.. and when need arises, we check whether we
already solved the problem beforehand.
Let me know if any doubt.. please upvote if it helps.