Reputation: 55
I am currently working on a project for college, first year computing class. With that being said, I am not asking for the answer, but I am asking more for some advice. In order to begin the project, I have decided to create a function called collatzSequencer that takes one argument type int.
Here is my function prototype:
int collatzSequencer(int);
Here is my function definition:
int collatzSequencer(int n) {
int stepCounter = 0;
if (n % 2 == 0) {
stepCounter += 1;
collatzSequencer(n / 2);
}
else if (n % 2 == 1) {
stepCounter += 1;
collatzSequencer((3 * n) + 1);
}
else if (n == 1) {
printf("%d\n", n);
printf("%d\n", stepCounter);
return 0;
Here is where I call the function within my main function:
int main(int argc, char* argv[]) {
int num = 5;
collatzSequencer(num);
return 0;
}
When I run my program, nothing happens and I exit with code 0. I have tried debugging my program, and I see that for some reason my IDE doesn't even run the collatzSequencer function when it is called. Although I am a beginner, I feel like I have enough knowledge to be able to find problems within only 48 lines of code, however I cannot find the issue here. Anyone have any ideas?
Upvotes: 1
Views: 45
Reputation: 311068
The function has undefined behavior because it does not return anything when n % 2 is equal 0 or 1 and the last else-if statement is not reached by the function control.
Moreover the variable stepCounter
can have the maximum value of 1 because it is a local variable of the function that in each recursive call of the function is initialized by zero.
int stepCounter = 0;
The function can be defined the following way as it is shown in the demonstrative program
#include <stdio.h>
size_t collatzSequencer( unsigned int n )
{
return n < 2 ? 0 : 1 + collatzSequencer( n % 2 == 0 ? n / 2 : 3 * n + 1 );
}
int main(void)
{
printf( "%zu\n", collatzSequencer( 27 ) );
return 0;
}
Its output is
111
as it is written in https://en.wikipedia.org/wiki/Collatz_conjecture
Upvotes: 0
Reputation: 64710
You are checking for three cases:
n % 2 == 0 (eg. n is Even)
n % 2 == 1 (eg. n is Odd)
n == 1 (eg. n is exactly ONE; this is also the only if-statement with a return)
Except: value 1
is an ODD number, which is captured by the second case.
Your code will never reach the n==1
case, because when n
is 1, it will always get captured by the Odd-value if-statement first.
Upvotes: 3