针对以下代码,当“n”大约到达10万时程序就会停止运行。我需要它一直运行到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;
}
}
chainLength > longestChain
不为真,则不会打印任何内容。也许你只是在等待的时间内没有找到更长的链条?尝试在该条件语句的else情况下打印一些东西(比如n
的值)。 - Jon Newmuis