首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从Uva法官那里得到3n+1problem的错误答案

从Uva法官那里得到3n+1problem的错误答案
EN

Stack Overflow用户
提问于 2015-10-10 08:06:20
回答 2查看 65关注 0票数 0

我尝试过几次提交3n+1问题,但是没能在Uva判断中被接受,我用java.Can写了这个程序,有人指出了我的程序中的错误。问题陈述:- problem&problem=36

我的节目:-

代码语言:javascript
运行
复制
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);
}

}
}

很抱歉我的代码缩进了错误的地方。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-10-11 06:28:29

我被UVa法官接受了。这个问题并没有考虑到第二个数字可以小于第一个数字。您必须考虑第二个数字是这个系列的开始的情况。

票数 0
EN

Stack Overflow用户

发布于 2015-10-10 12:46:46

我认为问题在于输入/输出。您的问题中的代码读取一行,然后打印一行。UVa页面上的输入/输出指定输入使用“序列”,并将“每个”用作输出。换句话说:读取所有输入行,计算,然后编写所有输出行。

下面是一些帮助您阅读所有输入行的代码(问题中的ReadLn方法看起来过于复杂):

代码语言:javascript
运行
复制
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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33051780

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档