1. 程式人生 > >尤拉計劃問題十四matlab實現

尤拉計劃問題十四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,找到之後往左第一列的資料便是結果,這個方法略有繁瑣,僅代表個人想法,有什麼好的方法可以推薦,歡迎留言!