3

我的 Euler Project 14 代码如下。我已经运行此代码超过 3 小时,输出结果似乎是无限的。当我测试单个数字如 11、27 时,它会快速输出 collat​​z 链号:14 和 111。但我不知道为什么它不能输出 1000000 个数的最大链数。

/*Problem 14
 * The following iterative sequence is defined for the set of positive integers:
 *          n -> n/2 (n is even)
 *          n -> 3n + 1 (n is odd) 
 * Using the rule above and starting with 13, we generate the following sequence:
 *               13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
 * It can be seen that this sequence (starting at 13 and finishing at 1) contains 
 * 10 terms. Although it has not been proved yet (Collatz Problem), it is thought 
 * that all starting numbers finish at 1.
 * 
 * Which starting number, under one million, produces the longest chain?
 * 
 * NOTE: Once the chain starts the terms are allowed to go above one million.
 */
package number;  
public class LongestCollatzSequence {
    public static int collatzNum(int n){
        int count = 0;
        while(n != 1){
            if(n%2 == 0)
                n = n/2;
            else 
                n = 3*n + 1;
            count++;
        }
        return count;
    }
    public static void main(String[] args) {
        int max = 0;
        for(int i = 10; i <= 1000000; i++){
            if(collatzNum(i) > collatzNum(max))
                max = i;
        }
        System.out.println(max);
    }
}

此外,我转向for(int i = 10; i <= 1000000; i++)for(int i = 10; i <= 10; i++)这么短的数字列表,它仍然一直在运行而没有输出。我的代码有什么问题?

这是另一个人的解决方案,rianjs.net代码是:

public class Problem014
{
    public static void main(String[] args)
    {
        long begin = System.currentTimeMillis();
        LinkedList<Long> list = new LinkedList<Long>();
        long length = 0;
        int res = 0;
        for(int j = 10; j < 1000000; j++){
            long i = j;
            while (i != 1){
                if (i % 2 == 0){
                    i /= 2;
                    list.add(i);
                }
                else{
                    i = (3 * i) + 1;
                    list.add(i);
                }
            }
            if(list.size() > length){
                length = list.size();
                res = j;
            }
            list.clear();
        }
        long end = System.currentTimeMillis();
        System.out.println(res+" with chain size: "+ length);
        System.out.println(end-begin + "ms");
    }
}

他的代码运行良好,我想知道为什么我的代码不能得到输出,这两种分辨率有什么区别?

4

4 回答 4

5

int n您的函数的参数collatzNum将溢出值 113383。如您所见,另一个实现使用 long 变量作为临时值。

除此之外,您可以通过不计算collatzNum(max)每次循环迭代来优化您的代码,但只有当 max 实际发生变化时,在这种情况下,您已经将 newcollatzNum(max)作为返回值从collatzNum(i).

于 2013-04-24T15:13:15.690 回答
3

您每次都在重新计算迄今为止发现的最长数字的长度。如果你只记得到目前为止你见过的最长的一个,它会减少到几秒钟。

顺便说一句,如果你想走得更快,你可以使用所有以前值的记忆。

static final short[] cache = new short[1000000];

public static int collatzNum(long n) {
    if (n == 1) return 1;
    if (n < cache.length) {
        int count = cache[((int) n)];
        if (count > 0)
            return count;
    }
    int next = (n & 1) == 0
            ? 1 + collatzNum(n >> 1)
            : 2 + collatzNum((n * 3 + 1) >> 1);
    if (n < cache.length)
        cache[((int) n)] = (short) next;
    return next;
}

static {
    for (int i = 10; i < cache.length; i *= 2)
        collatzNum(i - 1);
}

public static void main(String... ignored) {
    long start = System.nanoTime();
    int maxCount = 0, max = 0;
    for (int i = 1; i < 1000000; i++) {
        int count = collatzNum(i);
        if (count > maxCount) {
            maxCount = count;
            max = i;
        }
    }
    long time = System.nanoTime() - start;
    System.out.println("count=" + maxCount + ", value=" + max + ", took=" + time / 1000 / 1000.0 + " ms.");
}

在我的笔记本电脑上大约需要 19 毫秒。

注意:结果odd * 3 + 1总是偶数,所以你知道你可以将它除以 2。

于 2013-04-24T15:41:03.390 回答
1

这是另一个解决方案。它没有彼得的答案那么有效,但更容易理解:

public class P14 {

    public static void main(String[] args) {
        getMaxLength(1000000);
    }

    private static void getMaxLength(int threshold) {
        long maxLength = 1;
        int nr = -1;
        for (int i = 3; i < threshold; i++) {
            long sequenceSize = getSequenceSize(i);
            if (sequenceSize > maxLength) {
                maxLength = sequenceSize;
                nr = i;
            }
        }
        System.out.println(nr);
    }

    private static long getSequenceSize(int n) {
        long x = n;
        long count = 1;
        while (x > 1) {
            if ((x & 1) == 0) {        // x%2==0
                x = x >> 1;            // x=x/2
                count++;               // count=count+1
            } else {
                x = x + x + x + 1;     // x=3*x+1
                x = x >> 1;            // x=x/2
                count+=2;               
            }
        }
        return count;
    }

}

时间:1.5 秒(Peter 的解决方案在我的机器上需要 0.142 秒)

使用以下观察可以大大改善x它:如果我们有,2*x将在序列中多走一步(因为2*x是偶数)。这就是为什么我们可以忽略小于二分之一的数字。因此,使用以下getMaxLength方法:

    private static void getMaxLength(int threshold) {
        long maxLength = 1;
        int nr = -1;
        int start = (threshold>>1) - 1;      // start = threshold/2 - 1
        for (int i = start ; i < threshold; i++) {
            long sequenceSize = getSequenceSize(i);
            if (sequenceSize > maxLength) {
                maxLength = sequenceSize;
                nr = i;
            }
        }
        System.out.println(nr);
    }

计算大约需要0.8 秒

于 2014-11-16T02:01:39.943 回答
0

这是使用迭代和递归混合的问题的另一种解决方案。我希望它有所帮助,我还在代码中提供了一些注释以帮助更好地理解它。

private static int currentLongestChain = 1;

private static long number = 0;

public static void main(String[] args) {
    //TimeTable();
    PE_Problem_14();
}

private static void PE_Problem_14(){
    int longestChain = 1; // store longest chain
    for(long currentNumber = 1; currentNumber < 1000000; currentNumber++){
         if(currentNumber % 2 == 0){
            PE_Problem_14_even(currentNumber); // if currentNumber is even then invoke even helper method
         }else{
            PE_Problem_14_odd(currentNumber); // if currentNumber is odd then invoke odd helper method
         }

         if(currentLongestChain > longestChain){
            longestChain = currentLongestChain;  // update longestChain
            number = currentNumber;
            currentLongestChain = 0;
         }else{
            currentLongestChain = 0;
        }
    }
    System.out.println("longest chain: " + longestChain + " number: " + number); // print the result to the console screen
}

private static void PE_Problem_14_even(long evenNumber) {  // recursive method
    if(evenNumber <= 1) return;
    long localResult = (evenNumber/2);
    if(localResult % 2 != 0){
        ++currentLongestChain;
        PE_Problem_14_odd(localResult);
    }else {
        ++currentLongestChain;
        PE_Problem_14_even(localResult);
    }
}

private static void PE_Problem_14_odd(long oddNumber){  // recursive method
    if(oddNumber <= 1) return;
    long localResult = (3*oddNumber)+1;
    if(localResult % 2 == 0){
        ++currentLongestChain;
        PE_Problem_14_even(localResult);
    }else{
        ++currentLongestChain;
        PE_Problem_14_odd(localResult);
    }
}
于 2017-02-06T00:01:41.477 回答