Hey guys this is really messing with my head. Thanks in advance for any help yall can give me.
I am trying to write a simple number sequence type program for someone.. this code compiles and runs... but for some reason, I have no idea why, the program just seems to get stuck between two lines of code. I used stuff like:
if (x==113383){cout << "Line 00";}
to find out where it was going wrong, and I've inserted a comment into the code below. The line which preceeds the comment runs just fine, but the line after the comment apparently never happens when (x == 113383)!
So anyway here's the code. Go ahead and run it, please:
#include <iostream>
usingnamespace std;
int run_sequence(int x);
int main()
{
int largest, terms_ret, terms_max;
terms_max = 0; largest = 0;
for (int quantum=1; quantum < 1000000; quantum++)
{
terms_ret = run_sequence(quantum);
if (terms_ret > terms_max)
{
terms_max = terms_ret;
largest = quantum;
cout << "New longest sequence: " << largest << '\n';
cout << "Terms: " << terms_max << "\n";
}
}
cout << "The number between 1 and 1000000 which starts the longest sequence is: "
<< largest;
return 0;
}
int run_sequence(int x)
{
int cycle, w;
cycle = 0;
while (x != 1)
{
w = (x % 2);
// here's where I lose it when x == 113383 (wtf?)
if (w == 0)
{ x = (x / 2); }
else
{ x = ((x * 3) + 1); }
cycle++;
}
return cycle;
}
What goes on here? I am so lost.. is this an unusual problem?
Thanks for any suggestions.
- cPlusN()()b
p.s. I have used long int too, makes no difference, tho I didn't expect it to..
the statement: w = (x % 2);
runs, then, nothing. :/
UPDATE ok so
I used unsigned int for quantum and x and now it works perfectly. I think.
Can anyone please explain whats going on here? after all 1000000 is much more than 2 * 113383, and the value of x should never be negative, so why is the signed/unsigned causing trouble?
I'm scared.