循环停止运行java
发布时间:2020-12-15 04:58:31 所属栏目:Java 来源:网络整理
导读:对于下面的代码,当“n”大约为100,000时,它会停止运行.我需要它运行到100万.我不知道它出了什么问题,我还在学习 Java,所以代码中也可能存在简单的错误. public class Problem14{public static void main(String[] args) { int chainLength; int longestChain
对于下面的代码,当“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需要很长时间来保持它. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |