I was creating a similar, but not exact, program to the 3n + 1 problem on programming challenges, The function takes two integers a and b . if integer a is even, the program divides it by two, if not it will multiply it by three and add one . This is supposed to go on till a is one. When a is one, it will increment its original value by one. It keeps following this process till a is greater than y. The value of a gets printed to the command prompt if it is even. My main problem is that it starts printing all these weird long numbers to the screen, that are totally out of range if y is greater than or equal to three. Thanks
#include <iostream>
usingnamespace std;
int cyclerfunc( int a, int y);
int main()
{ int a, b;
while(cin>>a>>b){
cout<<a<<" "<<b<<" "<<cyclerfunc(a, b);
}
};
int cyclerfunc(int a, int y){
int n=0;
int cycler = 0;
int currentcycler = 0;
while(n <= y){
if (a % 2 == 0){
cout<<a<<endl;
a = a/2;
cycler++;
}
if(a == 1){
n++;
a = n;
if (currentcycler<cycler){
currentcycler = cycler;
}
else{
currentcycler = currentcycler;
}
}
else{
a= 3*a+1;
cycler++;
}
}
return currentcycler;
}
The strange values are where the variable a overflows beyond the capacity of that type. I'm not sure how the value of a is ever supposed to reach 1, since on each pass of the loop, a = 3*a+1; is always executed. The code a = a/2; is executed some of the time. Thus a is growing far faster than it is getting smaller, and can never go down towards 1. At least that's how it looks to me.
your program will run an infinite loop because n which is 0 will always be < y once it is initialized greater than it. That would explain why it keep outputting numbers continuously. and also what @Chervil said also.
if your using Visuall c++ as your ide, use the debug funtion and add the watch variable functionality. it will show youw what you program does line by line and how each variable changes
I agree with geosnipes, learn to use the debugger (no matter which IDE you use) to step through the code one line at a time and watch the values of variables.