Reputation: 13910
I recently started trying to complete some UVA problems but I got stuck on my first one. the problem is the 3n + 1. I have been able to make some progress and almost completed what was required except for the increment.
InputStreamReader inputStream = new InputStreamReader(System.in);
BufferedReader buffReader = new BufferedReader(inputStream);
try
{
String input = buffReader.readLine();
String[] brokenArray = input.split("\\s");
int a = Integer.parseInt(brokenArray[0]);
int b = Integer.parseInt(brokenArray[1]);
int c = 1;
System.out.print(a +" "+b+" ");
//if( a <= b )
while ( a!= b) {
while (a != 1) {
if((a%2)!= 0) {
c++;
a = 3*a+1;
} else {
c++;
a = a/2;
}
}
System.out.println(c);
**a ++;**
}
so basically its supposed to take 2 inputs and run a count which is c of the operations performed.. but after it finishes counting the operations on a number before getting to one it has to move to the second number therefore I put an increment to move on to the next one. It increments the first time but the variable a at the bottom stays one so im constantly icrementing one rather than incrementing 2, 3, etc.
Upvotes: 0
Views: 136
Reputation: 13910
well here is the link to the actual problem, sample inputs and sample outputs..
http://uva.onlinejudge.org/external/1/100.pdf
but thanks guys, for shedding light on the problem..I have to initialize a new variable.
Upvotes: 0
Reputation: 11066
Your inner loop will always ensure that a == 1
when it ends (because it loops while a != 1
, so it ends only when a == 1
). Then, your outer loop increments a
before it repeats. That is why you are always incrementing 1
. So, unless b == 2
, you are always going to get stuck.
Upvotes: 2