欧拉计划14题 matlab 学习笔记 +excel输出+调试程序

    xiaoxiao2022-07-14  169

    第十四题

    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. 求:上述小于1000000数中拥有最长序列的初始数值

    思路

    先写出单个数值的循环序列terms计数找到最大的计数数值 note:问题最后面提示,跑的时候数会超过一百万,但要求starting number小于一百万,所以如果条件用n<1000000时,最大的starting number远小于一百万。 %% 14 n=1; i=1; k=1; I=[]; while k<1000000 %starting number 小于一百万(用k,不用n,理由如上note) if mod(n,2)==0 %如果是偶数,n/2,否则3*n+1 n=n/2; else n=3*n+1; end i=i+1; %i为计算循环次数 if n==1; %做判断,当n==1时,进行新循环,否则仍然循环上述If条件 I=[I,i]; %当为1的时候,记录循环次数i k=k+1; %k,starting number 加一 n=k; i=0; %循环次数归零 end end max(I) %判断最大的循环次数 % [x,y]=find(I==?) %输出之后再搜索位置,位置即为要求的starting number

    结果: 837799

    I=524 其他参考:https://blog.csdn.net/qq_38910271/article/details/83081453 这个代码速度更快(具体见链接),只跑了几秒(上面那个要跑很久)

    %% 14 其他人参考代码 tic clear,clc i = 1; j = 0; for n = 1000000:-1:1 x = n; while n~= 1 %如果满足n不等于1,则执行下列命令 if mod(n,2) == 0 n = n/2; i = i+1; else n = n*3+1; i = i+1; end end B(x,1) = x; B(x,2) = i; %第一列记录x,第二列记录x的循环次数 if i > j %记录最大的循环次数 j = i; end i=1; end j toc xlswrite('C:\Users\admin\Documents\MATLAB\1.xlsx',B) %输出成excel

    反思:代码不够简洁,时间太长

    补充 调试程序步骤 1、选择断点(按run会到断点位置停止) 2、按F11或F10即可进行逐步调试(必须先运行,进入调试状态)

    最新回复(0)