循环停止运行java

sta*_*Err 3 java

对于下面的代码,当"n"大约为100,000时,它会停止运行.我需要它运行到100万.我不知道它出了什么问题,我还在学习Java,所以代码中也可能存在简单的错误.

 public class Problem14{
public static void main(String[] args) {
    int chainLength;
    int longestChain = 0;
    int startingNumber = 0;
    for(int n =2; n<=1000000; n++)
    {
        chainLength = getChain(n);
        if(chainLength > longestChain)
        {
            System.out.println("chainLength: "+chainLength+" start: "+n);
            longestChain = chainLength;
            startingNumber = n;
        }
    }

    System.out.println("longest:"+longestChain +" "+"start:"+startingNumber);
}
public static int getChain(int y)
{
    int count = 0;
    while(y != 1)
    {
        if((y%2) == 0)
        {
            y = y/2;
        }
        else{
            y = (3*y) + 1;
        }
        count = count + 1;
    }

    return count;   
}
}
Run Code Online (Sandbox Code Playgroud)

Kum*_*tra 6

long用作data type 代替 int

我希望这一点能够发现,这个数字确实高于 1000000,所以变量y需要long保持它.

  • @KumarVivekMitra如果你已经解释了为什么,也许人们不会那么快就给你负面的分数,但正如我说你钉它:). (4认同)

Dan*_*Dan 5

它是y的数据类型.它应该很.否则它会回合到二十亿.

我以为我认识到这一点 - 这是欧拉问题14.我自己就是这样做的.