How a recursive function works in C

The fun (n) function is defined as such:

fun(n) = 1                 (if n <=1)
fun(n) = fun(n/2)          (if n is even)
fun(n) = 2*fun((n-1)/3)    (if n> and n is odd)

I am trying to write a recursive function to calculate and return the result. I just started to study recursion, I lost it while performing this function. Can someone correct me and explain to me? Thank!

Here is what I did:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h> 
#include <math.h>

int fun(int n);

int main()
{
    int num;

    printf("\nEnter a number: ");
    scanf("%d", num);
    printf("Result = %d\n", fun(num));
    return 0;
}

int fun(int n)
{
    if (n <= 1)
    {
        return 1;
    }

    else if (n % 2 == 0)
    {
        return fun(n / 2);
    }

    else if ((n > 1) && (n % 2 == 0))
    {
        return 2 * fun((n - 1) / 3);
    }
}

Expected Result:

Enter a number: 13
Result = 2

Enter a number: 34
Result = 4

The result I get instead is:

Enter a number: 13
Result = 1

Enter a number: 34
Result = 1
+4
source share
5 answers

scanftakes a pointer to intas an argument to %d, i.e.

scanf("%d", &num);

In addition, your function fundoes not handle all cases and may fall from below:

if (n <= 1)
{
    return 1;
}
else if (n % 2 == 0)
{
    return fun(n / 2);
}
else if ((n > 1) && (n % 2 == 0))
{
    return 2 * fun((n - 1) / 3);
}

else if , n % 2 == 0 . n > 1 , n <= 1 .

:

else
{
    return 2 * fun((n - 1) / 3);
}
+6

- else if. :

else if ((n % 2) != 0)
+2

, n , . , , n .

, , , :

int fun(int n)
{
    if(n <= 1)
        return 1;
    if(n % 2 == 0)
        return fun(n/2);
    //No need for a condition, we know the last one must be satisfied
    return 2 * fun((n-1)/3);
}

, " ", , .

+1

, if :

else if ((n > 1) && (n % 2 != 0))

!= ==.

+1

else if ((n > 1) && (n % 2 == 0))

, , else no else if - .

0
source

Source: https://habr.com/ru/post/1532499/


All Articles