最长柯拉兹序列

3
在做我的Java作业,实现科拉兹猜想时,我想到了一个不同的目标,那就是找到最长的科拉兹序列。我的程序如下计算步骤:
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);
    }

}

我想找到最高的步数。


6
那么你的问题是什么? - High Performance Mark
bilgi返回计数,并记住最高的计数。但是使用long来处理数字,因为它们可能会变得非常大。 - Daniel Fischer
1
我不想逐个检查它们,例如如果我从1到100运行此代码块,哪个序列将是最高的。最长的步骤。 - Alpan Karaca
但最长的序列可能具有无限长度。事实上,可以证明对于任何数字n,都存在一个长度为n的Collatz序列。因此,期望花费很长时间寻找最长的序列。 - user85109
与斐波那契数列不同的是,考拉兹猜想中的数字在范围1..n内可以通过k→3k+1步骤映射到范围之外(更高的范围)。因此,从1..100运行将需要计算超出该范围的选择点的考拉兹猜想。27的示例。与斐波那契数列不同,范围的运行时间不确定(对于大的n甚至没有界限,尽管已经验证了64位自然数)。 - smci
4个回答

3
static int bilgi(int n) {
    int result = n;
    if (result <= 1) return 1;
    if (result % 2 == 0) return 1+bilgi(result/2);
    return 1+bilgi(3*result+1);
}

然后,您收集bilgi(i)调用的结果并选择最大值。

2
任何小于一亿的起始数字所得到的最长进展为63,728,127,共有949步。对于小于十亿的起始数字,最长进展为670,617,279,共有986步,而对于小于一百亿的数字,最长进展为9,780,657,630,共有1132步。
来源:http://en.wikipedia.org/wiki/Collatz_conjecture

1
OP的目标是编写一个Java类来确定这个结果,而不是仅仅相信维基百科的说法。 - Ryan B.

0
如果你正在寻找1和100之间的最大值,你可以替换以下代码:
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(),因为它比你的更快。

*/


0

我知道这是一个老问题,但我刚刚解决了它,并建议任何人使用arraylist并获取.size()。我是用这种方式做的,因为我也想看到值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接