冰雹序列是一个数字列表: 如果n是偶数,则n = n / 2 如果n是奇数,则n =(n * 3)+ 1 如果n为1,则序列结束。
每次执行步骤时,都会为序列添加+1。我试图找到小于1000的最大序列。这是我的代码。
import java.lang.Math;
public class HailStone
{
public static void main(String[] args)
{
int sequenceList = 0;
int sequenceMax = Integer.MIN_VALUE;
for(int i = 0; i < 10; i++)
{
int count = 0;
while(count == 0)
{
int sequenceNum = i;
if(sequenceNum == 1)
{
sequenceList++;
sequenceMax = Math.max(sequenceMax, sequenceList);
count++;
}
if(sequenceNum % 2 == 0)
{
sequenceList++;
sequenceNum = sequenceNum/2;
}
else if(sequenceNum % 2 != 0)
{
sequenceList++;
sequenceNum = (sequenceNum * 3) + 1;
}
}
}
System.out.println("Max sequence: " + sequenceMax);
}
}
我的代码编译但它永远不会完成。我可能遗漏了一些非常明显的东西,但我多次检查过它。
我知道我可以使用while(true)和break但我编辑它以查看是否存在问题。不要批评我的格式,我只需要为什么它不起作用。
答案 0 :(得分:0)
你开始进入无限循环:
int sequenceNum = 0;
和
count = 0;
因此它会一直落入if
条件:
if(sequenceNum % 2 == 0)
{
sequenceNum++;
sequenceNum = sequenceNum/2;
}
所以sequenceNum
保持为零(0/2 == 0)且sequenceNum
不断增加。
缓存先前结果的替代解决方案(如上面其中一条评论中建议的ajb):
class HailStone {
static Map<Integer, List<Integer>> cache = new HashMap<>();
public static void main(String[] args){
runMainLogic();
}
private static void runMainLogic() {
int runner = 1;
int maxSize = 0;
int maxNum = 0;
List<Integer> seq;
while(runner < 1000) {
if (cache.get(runner) == null) {
seq = calcHailStone(runner);
cache.put(runner, seq);
} else {
seq = cache.get(runner);
}
if (maxSize < seq.size()) {
maxSize = seq.size();
maxNum = runner;
}
runner ++;
}
System.out.println("maxNum = " + maxNum);
System.out.println("maxSize = " + maxSize);
System.out.println(Arrays.toString(cache.get(maxNum).toArray()));
}
private static List<Integer> calcHailStone(int runner) {
List<Integer> res = new LinkedList<>();
while (true) {
if (runner == 1) {
res.add(1);
break;
} else if (runner % 2 == 0) {
runner /= 2;
res.add(runner);
} else {
runner = runner * 3 + 1;
res.add(runner);
}
}
return res;
}
}