对于下面的代码,当"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)
请long用作data type 代替 int
我希望这一点能够发现,这个数字确实高于 1000000,所以变量y需要long保持它.
| 归档时间: |
|
| 查看次数: |
155 次 |
| 最近记录: |