Collatz Conjecture

Hi all,

I'm trying to write a program in C++ which tests the Collatz Conjecture. The Collatz Conjecture states that you start with a number, and if that number is equal you divide it by 2; if the number is odd, you multiply it by 3 and add 1. You then apply the appropriate sum to this result depending on whether it is odd or even, and continue until eventually you end up with 1.

I'm having trouble representing odd and equal numbers. So far I've written two functions:

unsigned int odd(unsigned int num)
{
cout<<num<<" is odd, so multiply by 3 and add 1"<<endl;
num=num*3+1;

return num;
}

unsigned int even(unsigned int num)
{
cout<<num<<" is even, so divide by 2"<<endl;
num=num/2;

return num;
}

The flow logic is below:

int main()
{

unsigned int num;

cout<<"Enter a whole number: "<<endl;
cin>>num;


while (num!=1)
{
for(int i=2;i<=4294967294;i++)
{
if (num==i)
{
even(num);

}

else
{
odd(num);

}
}
}
}

What's happening is whatever number I enter, I end up with an infinite loop of "<number entered> is odd, so multiply by 3 and add 1" regardless of whether the number is odd or even. I don't understand why, if the number IS even, this part of the code is being skipped.

Any help or advice on this would be greatly appreciated. I'm relatively certain that I'm going about this correctly but if not then please let me know!
Use % operator. It returns the remainder of division. When dividing by 2, odd numbers have remainder 1 and even have 0.
Hi hamsterman, thanks for your reply.

I don't quite understand: where should I be using the modulus?
bool IsNumberOdd(int num)
{
return ((num % 2) == 1);
}

is a way to do it. if((num % 2) == 1) also works though.
Or you can just say if(num%2), which will return true if the number is odd.
Last edited on
Ah ha! Yes I see it now :) Great, thanks a lot!
Tested it and it works like a charm :) thanks again!
Topic archived. No new replies allowed.