【问题标题】:Longest Collatz Sequence最长科拉兹序列
【发布时间】:2012-10-22 12:20:28
【问题描述】:

在做实现Collatz Conjecture 的Java 作业时,我想到了一个不同的目标,即找到最长的Collat​​z 序列。我的程序计算步骤如下:

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返回计数,并记住最高的。但是使用long 作为数字,它们会变得非常大。
  • 我不想一个一个地检查它们,例如,如果我从 1 到 100 运行这个 bilgi,哪个序列将是最高的。最长的一步。
  • 但是最长的序列可能有无限长。事实上,可以证明对于任何数 n,都存在一个长度为 n 的 Collat​​z 序列。所以期待等待很长时间才能找到 LONGEST 序列。
  • 关于 Collat​​z 的要点,与斐波那契不同,1..n 范围内的数字可以映射(通过 k→ 3k+1 步)到范围之外(更高)。因此,从 1..100 开始运行也需要为该范围之外的选择点计算 Collat​​z。 Example for 27。与斐波那契不同,范围的运行时间不是确定性的(对于较大的 n,甚至是有界的,尽管它已针对 64 位自然数进行了验证)。

标签: algorithm numbers sequence collatz highest


【解决方案1】:
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】:

    任何小于 1 亿的初始起始数字的最长级数是 63,728,127,即 949 步。对于小于 10 亿的起始数字是 670,617,279,有 986 个步骤,对于小于 100 亿的数字,它是 9,780,657,630,有 1132 个步骤

    来源:http://en.wikipedia.org/wiki/Collatz_conjecture

    【讨论】:

    • OP 的目标是编写一个 java 类来确定这个结果,而不是按照维基百科的说法。
    【解决方案3】:

    如果您正在寻找 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() 因为它比你的快得多。 */

    【讨论】:

      【解决方案4】:

      我知道这是一个老问题,但我只是在解决它,我建议任何这样做的人,只需使用数组列表并获取 .size(),我就是这样做的,因为我想看看价值观。

      【讨论】:

        猜你喜欢
        • 2021-11-20
        • 2019-01-03
        • 1970-01-01
        • 2021-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多