Problem: Define a function, named ramanujan. Which takes, as its only argument, the depth of a rational approximation to the previous nested expression. For example, if depth is 0, Ramanujan should return the square root of 6. If depth is 1, Ramanujan should return the value of √6 + 2√7. If the depth is 2, the return value must be the value of √6 + 2√7 + 3√8. Your function must implement a recursive process.
I managed to solve the problem iteratively and print the results in main:
#include <iostream>
#include <math.h>
using namespace std;
float ramanujan(int depth){
int subradical = 6;
int factor = 1;
float value = 0;
for (int i=depth; i>=0; i--){
if (i==depth) {
value = (factor+i)*sqrt(subradical+i);
} else {
value = (factor+i)*sqrt(subradical+i + value);
}
}
return value;
}
int main() {
float total = ramanujan(3); //Funciona en caso de que sea 0, 1, 2...
cout << total;
return 0;
}
What I need is a way to implement the solution I already have recursively. And that the recursive function only receives one parameter (the depth)
You can see that the expression looks like the following, with a = 1 and b = 6 :
Mathematically you can compact it like this:
The hard work is already done. You just have to write it as code and it would look like this:
But there's a problem. The code will run indefinitely until it runs out of memory.
So as the depth increases, you add a parameter
maxDepth
that if itdepth
is greater than or equal to, as in the radical you have a sum, you return the neutral element (0) so as not to alter the result.You can try the code here .