My program is outputting out of range numbers

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
using namespace 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;
}
Last edited on
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.
Can you please elaborate on what you mean Chervil, I don't really understand. Thanks
Last edited on
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
Last edited on
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.
I will use the debugger, thanks guys for all your help. I didn't realize had to change n.
Topic archived. No new replies allowed.