1

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.

enter image description here

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)
igor
  • 103
  • 8
  • `rekurzija` and `recursion` are named differently. Maybe you forgot to change the names while uploading the snippet? – wookiekim Jan 16 '20 at 00:35
  • 1
    Don't us x++ and --i when you are not saving the variable, just call sqrt(k/subN+rekurzija(n-1, k, flag-1, subN-2, rep-1)); – Simson Jan 16 '20 at 00:36
  • @wookiekim I did, thanks, but that does not solve the issue. – igor Jan 16 '20 at 00:37

1 Answers1

1

When dividing two int you get integer division, where the answer is an integer. Replace at least one of the operands with a double to get floating-point calculations.

double recursion(int n, int k, int flag, int subN, int rep)
{
    if(rep == 0)
        return 0;
    if(flag == 0)
        return sqrt((double)n/subN+recursion(n, k+1, flag+1, subN-2, rep-1));
    else
        return sqrt((double)k/subN+recursion(n-1, k, flag-1, subN-2, rep-1));
}

or even better just change the function signature to double recursion(double n, double k, int flag, double subN, int rep)

Simson
  • 3,373
  • 2
  • 24
  • 38