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
source
share