gpt4 book ai didi

java - 循环停止运行java

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:34:55 25 4
gpt4 key购买 nike

对于下面的代码,当“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;
}
}

最佳答案

请使用long作为数据类型而不是 int

我想让大家明白这一点,这个数字确实高于 1000000,所以变量 y 需要 long 来保存它.

关于java - 循环停止运行java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12008827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com