3n+1 problem at UVa
Posted
by
ShahradR
on Stack Overflow
See other posts from Stack Overflow
or by ShahradR
Published on 2010-12-16T17:01:20Z
Indexed on
2010/12/26
6:54 UTC
Read the original article
Hit count: 424
Hello,
I am having trouble with the first question in the Programming Challenges book by Skiena and Revilla. I keep getting a "Wrong Answer" error message, and I don't know why. I've ran my code against the sample input, and I keep getting the right answer. Anyways, if anyone could help me, I would really appreciate it :)
Here is the problem URL: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=29&page=show_problem&problem=36
And here is the code:`
import java.util.Scanner;
public class Main
{
static Scanner kb = new Scanner(System.in);
public static void main(String[] args)
{
while (kb.hasNext())
{
long[] numericalInput = {0, 0};
long i = kb.nextLong();
long j = kb.nextLong();
if (i > j)
{
numericalInput[0] = i;
numericalInput[1] = j;
}
else
{
numericalInput[0] = j;
numericalInput[1] = i;
}
long maxIterations = 0;
for (long n = numericalInput[0]; n <= numericalInput[1]; n += 1)
{
if (maxIterations < returnIterations(n))
maxIterations = returnIterations(n);
}
System.out.println(i + " " + j + " " + maxIterations);
}
System.exit(0);
}
public static long returnIterations(long num)
{
long iterations = 0;
while (num != 1)
{
if (num % 2 == 0)
num = num / 2;
else
num = 3 * num + 1;
iterations += 1;
}
iterations += 1;
return iterations;
}
}
` EDIT: I think the problem is with the output. I tried to make it accept all the input first and then display all the answers at once, but I didn't know the terminating condition. I resorted to this method, but I'm not sure that's what the judge wants...
© Stack Overflow or respective owner