James
James

Reputation: 1

(Yet Another) UVa 3n+1 Help Question

I have been beating my head against the wall trying to figure out why this is returning "Wrong Answer." I'd greatly appreciate any feedback.

Edit: I reposted the code, and this version finally fixed the "Runtime Error" by allowing for multiple spaces between the number pair. It now is saying "Wrong Answer" but as far as I can tell, I copied the given algorithm verbatim, so I'm at a loss.

Thanks.

The Problem

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;


public class Main {

public static void main(String[] args) {
   Main mine = new Main();
   mine.begin();
}

public void begin(){
    BufferedReader sys = new BufferedReader(new InputStreamReader(System.in));
    String[] pair;
    try{
        while((pair=sys.readLine().split(" +")).length==2){
            System.out.println(pair[0]+ " " +pair[1] + " " + getMax(Integer.parseInt(pair[0]),Integer.parseInt(pair[1])));
        }
    }catch(IOException ex){
        return;
    }
}

private String getMax(int a, int b){
    int maxcount,thiscount, num, n;

    for(maxcount = -1, num =Math.min(a, b); num <= Math.max(a, b); num++ ){
        for(n = num, thiscount = 1; n!=1; thiscount++){
            if(n%2==0)n=n/2;
            else n = 3*n +1;
        }
        if(thiscount>maxcount) maxcount = thiscount;
    }
    return String.valueOf(maxcount);
}
}

Upvotes: 0

Views: 832

Answers (4)

aked
aked

Reputation: 5815

I think the most important thing in UVA judge is:

  1. Get the output exactly the same. No extra lines at the end.
  2. Never throw exception just return or break with No output for Outside boundary parameters.
  3. Output is case sensitive
  4. Output parameters should maintain spaces as shown in the problem

Here is link at Stackoverflow : https://stackoverflow.com/a/14632770/1060656

Upvotes: 0

CoderTao
CoderTao

Reputation: 4001

If you're getting a wrong answer, and your program works on the samples, then the problem is probably tied to the fact that you're using ints rather then longs.

For the 3n+1 problem, the intermediate values can grow to be larger then an int can handle (2,147,483,647), and it's a common way for judge data to be evil.

Upvotes: 0

Jeff Mercado
Jeff Mercado

Reputation: 134521

You might want to reconsider how you parse the lines. I believe the only lines that could have runtime errors in your code are the integer parsing ones. You're assuming that each i and j are separated by a single space. The question makes no mention of how much whitespace will be on a line.

Upvotes: 0

Lee Reeves
Lee Reeves

Reputation: 406

while(num<4){
...

Is the input always limited to 4 lines?

Upvotes: 2

Related Questions