欧拉计划问题十四matlab实现

Problem 14 :Longest Collatz sequence

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.

思路 : 

最长的考拉兹数列就是任何一个数,如果是偶数就除以2,奇数就乘3加1,按照这个原则,任何数都可以最后到一。比如从13开始,到1结束的考兹拉数列总共有10个现在让我们求一百万一下的最长的考兹拉数列,那我们还是采用一个for回圈,从后往前收敛速度还是很快的,用了7.970888秒就完成了。

代码 :

tic
clear,clc
i = 1;
j = 0; 
for n = 1000000:-1:1
        x = n;
        while n ~= 1
            if mod(n,2) == 0
                n = n/2;
                i = i + 1;
            else
                n = 3*n +1;
                i = i + 1;
            end
        end
        B(x,1) = x;                     %save to matrix
        B(x,2) = i;           
    if i > j
        j = i;
    end
    i = 1;   
end
j
toc
xlswrite('C:\Users\dell\Desktop\Data.xlsx',B)           %save data to excel and display desktop

结果 :837799

注意 :最后输出的数据表格第二列里查找525,找到之后往左第一列的数据便是结果,这个方法略有繁琐,仅代表个人想法,有什么好的方法可以推荐,欢迎留言!

猜你喜欢

转载自blog.csdn.net/qq_38910271/article/details/83081453