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数中拥有最长序列的初始数值
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即可进行逐步调试(必须先运行,进入调试状态)
