我尝试过几次提交3n+1问题,但是没能在Uva判断中被接受,我用java.Can写了这个程序,有人指出了我的程序中的错误。问题陈述:- problem&problem=36
我的节目:-
import java.io.*;
import java.util.*;
class Main
{
    static String ReadLn (int maxLg)  // utility function to read from stdin
    {
       byte lin[] = new byte [maxLg];
       int lg = 0, car = -1;
       String line = "";
        try
        {
        while (lg < maxLg)
        {
            car = System.in.read();
            if ((car < 0) || (car == '\n')) break;
            lin [lg++] += car;
        }
    }
    catch (IOException e)
    {
        return (null);
    }
    if ((car < 0) && (lg == 0)) return (null);  // eof
    return (new String (lin, 0, lg));
}
public static void main (String args[])  // entry point from OS
{
   Main myWork = new Main();  // create a dinamic instance
    myWork.Begin();            // the true entry point
}
void Begin()
{
    String input;
    while((input=Main.ReadLn(255))!=null){
    StringTokenizer str=new StringTokenizer(input);
    int n1=Integer.parseInt(str.nextToken());
    int n2=Integer.parseInt(str.nextToken());
    int max=0;
    for(int i=n1;i<=n2;i++)
    {
        int no=calculate(i,0);
        if(max<no){
            max=no;
        }
    }
    System.out.println(n1+" "+n2+" "+max);
    }
}
static int calculate(int a,int sum){
if(a==1)
{
    return sum+1;
}
else if(a%2==0)
{
    sum+=1;
    return calculate(a/2,sum);
}
else
{
    sum+=1;
    return calculate((3*a+1),sum);
}
}
}很抱歉我的代码缩进了错误的地方。
发布于 2015-10-11 06:28:29
我被UVa法官接受了。这个问题并没有考虑到第二个数字可以小于第一个数字。您必须考虑第二个数字是这个系列的开始的情况。
发布于 2015-10-10 12:46:46
我认为问题在于输入/输出。您的问题中的代码读取一行,然后打印一行。UVa页面上的输入/输出指定输入使用“序列”,并将“每个”用作输出。换句话说:读取所有输入行,计算,然后编写所有输出行。
下面是一些帮助您阅读所有输入行的代码(问题中的ReadLn方法看起来过于复杂):
public static List<int[]> readCycleRanges() throws Exception {
    List<int[]> cycleRanges = new ArrayList<>();
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String line = br.readLine();
    while (!(line == null || line.trim().length() == 0)) {
        StringTokenizer st = new StringTokenizer(line, " ");
        int i = Integer.valueOf(st.nextToken());
        int j = Integer.valueOf(st.nextToken());
        cycleRanges.add(new int[] { i, j, 0 });
        line = br.readLine();
    }
    return cycleRanges;
}https://stackoverflow.com/questions/33051780
复制相似问题