Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does recursive function in C works

Function fun(n) 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'm trying to write a recursive function to compute and return the result. I just started learning recursion, I got kind of lost while doing this function. Can someone correct me and explain to me? Thanks!

Here's 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 output:

Enter a number: 13
Result = 2

Enter a number: 34
Result = 4

Output I'm getting instead:

Enter a number: 13
Result = 1

Enter a number: 34
Result = 1
like image 880
unintendedjoy Avatar asked Dec 26 '22 11:12

unintendedjoy


2 Answers

scanf takes a pointer to int as argument for %d, i.e.,

scanf("%d", &num);

Also, your function fun does not handle all cases and may fall off the bottom:

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);
}

The last else if condition is never met, because the previous check for n % 2 == 0 already returns in that case. Also the n > 1 is pointless because the first n <= 1 returns in all other cases.

You can simply make it:

else
{
    return 2 * fun((n - 1) / 3);
}
like image 136
Arkku Avatar answered Dec 28 '22 13:12

Arkku


The culprit is the last else if condition. Change it to:

else if ((n % 2) != 0)
like image 30
Green goblin Avatar answered Dec 28 '22 14:12

Green goblin