在做我的 Java 作业(即实现“Collatz 猜想”)时,我想到了一个不同的目标,即找到最长的 Collatz 序列。我的程序计算步骤如下:
public class Collatz {
static int count = 0;
static void bilgi (int n){
int result = n;
System.out.println("Result: "+result+ " Step: "+count);
if (result <= 1) {
result = 1;
} else if (result%2 == 0){
result = result/2;
count = count + 1;
bilgi(result);
} else {
result = (result*3)+1;
count = count + 1;
bilgi(result);
}
}
public static void main(String[] args) {
bilgi(27);
}
}
我想找到最高步数。
然后收集
bilgi(i)
调用的结果并选择最大值。
public static void main(String[] args) {
bilgi(27);
}
与:
public static void main(String[] args) {
static int maxcountsofar = 0;
static int start = 0;
static int thisone = 0;
for (int iloop = 1; iloop <= 100; iloop++)
{
thisone = bilgi(iloop);
if (thisone > maxcountsofar)//if this one is bigger than the highest count so far then
{
start = iloop;//save this information as best so far
maxcountsofar = thisone;
}
}
System.out.println("Result: " + start.Tostring() + " Step: " + maxcountsofar.Tostring() );
//I know this is a really old post but it looked like fun.
}
/* 另外,将 println() 从 bilgi() 函数中取出,它会为遇到的每个步骤生成一行,这将毫无价值且极其耗时。
使用 Vesper 的 bigli() 因为它比你的快得多。 */