欧拉计划问题十四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,找到之后往左第一列的数据便是结果,这个方法略有繁琐,仅代表个人想法,有什么好的方法可以推荐,欢迎留言!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值