Reputation: 3523
While simulating the Colatz Conjecture problem i have made recursion when i want to print the count number in the recursion i get the result i need but when the function return the result it gives me weird numbers, why is that?
#include <stdio.h>
#include <stdlib.h>
int divide(int n,int count){
if(n<=1){printf("%d ",count);return count;}
if(n%2==1){divide(n=3*n+1, ++count);}
else{divide(n/=2, ++count);}
}
int main(void) {
printf("%d ",divide(10,1));
return 0;
}
Upvotes: 1
Views: 128
Reputation: 19453
A. you need to return the returned value from the recursion calls.
B. why do you assign a value to n
in the calls to divide?
#include <stdio.h>
#include <stdlib.h>
int divide(int n,int count){
if(n<=1){printf("%d ",count);return count;}
if(n%2==1)
{
return divide(3*n+1, ++count);
}
else
{
return divide(n/2, ++count);
}
}
int main(void) {
printf("%d ",divide(10,1));
return 0;
}
Upvotes: 3
Reputation: 477378
You need to return the results of the recursive calls:
if (n % 2) { return divide(3 * n + 1, count + 1); }
// %%%%%%
else { return divide(n / 2, count + 1); }
Note that there's no point in assigning to the local variables, so I've changed that to simple computations.
Upvotes: 8