I'm trying to do a recursion for my coding class in C language. For some reason, the solution that I get is wrong, event though I made sure multiple times that the formula is correct.
This is what I am supposed to replicate in code.
double recursion(int n, int k, int flag, int subN, int rep)
{
if(rep == 0)
return 0;
if(flag == 0)
return sqrt(n/subN+recursion(n, ++k, ++flag, subN-2, --rep));
else
return sqrt(k/subN+recursion(--n, k, --flag, subN-2, --rep));
}
int main()
{
int n;
scanf("%d", &n);
printf("%f", recursion(n, 0, 0, 2*n, n));
return 0;
}
For n = 6, I get 1.021897, for n = 7, I get 1.005430
My solution:
- n - the number we are starting from, user inputs this number in console
- k - this integer is supposed to be that counter from 1
- subN - this is the number we are dividing n with
- rep - acts as a counter to know when the recursion should stop (it always ends after n cycles)