1.自己的实现代码
function c = collatz(n) i=1; c(i)=n; if n==1 return; end for i=1:99 if mod(c(i),2) c(i+1)=3*c(i)+1; else c(i+1)=c(i)/2; end if c(i+1)==1 return; end end
2.别人的实现代码
function c = collatz(n) c = []; while n ~= 1 c = [c,n]; if mod(n,2) n = 3*n+1; else n = n/2; end end c = [c,1]; end
3.对比得出,1.他人对while循环应用更熟练。2.对数列的应用更灵活c=[c,n], c=[c,1]
cody challenge problem21 return the 3n+1 sequence for n 代码对比
原文:https://www.cnblogs.com/tanyuanqing/p/13726294.html