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

尤拉計劃問題十二matlab實現

Problem 12 :

The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be                   1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:

                                    1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

Let us list the factors of the first seven triangle numbers:

1: 1
           3: 1,3
           6: 1,2,3,6
         10: 1,2,5,10
         15: 1,3,5,15
         21: 1,3,7,21
         28

: 1,2,4,7,14,28

We can see that 28 is the first triangle number to have over five divisors.

What is the value of the first triangle number to have over five hundred divisors?

思路 : 

據題意,三角數是由自然數迭代相加而產生的,比如第七個三角數28 = 1 + 2 + 3 + 4 + 5 + 6 + 7,而其有1,2,4,7,14,28等6個除數,現在題目想讓我們求除數大於500個的三角數是什麼?

我的思路還是迭代,比如說給你一個三角數,就讓該三角數在for迴圈裡進行迴圈,從1開始除,若能被整除,則讓除數個數加1,一直除到本身,若除數個數小於500,則除數個數清零,產生新的三角數,再進入迴圈,計算的資料量也是非常大,思路就是直接法破解!

tic
a = 0;  %lteration triangle number
k = 1;  %number pointer
t = 1;  %the first triangle number
i = 0;  %the nuber of divisors
while i < 500
    for j = 1:t
        if mod(t,j) == 0
            i = i + 1;
        end
    end
    if i < 500
        i = 0;
        k = k + 1;
        a = 1:k;
        t = sum(a);
    else
        disp(t);
        break
    end
end
t
toc

結果 :76576500

小結 :

這個方法也是暴力破解,我還是先擺一張圖片讓大家感受一下:

程式運行了7447.447333秒,共計124分鐘左右,兩個小時,回頭看看,發現我自己真是很執著,沒有任何的技巧,硬算出來的,希望能拋磚引玉!