Collatz Conjecture using for loop
이전 댓글 표시
Consider the following algorithm
- start with positive integer
- if the number is even, divide by 2 if not multiply it by 3 and add one
- repeat the process until the number 1 is obatined
We ae required to create a function that takes two inputs 'n'=positive integer and 'max_steps' and returns the number of steps rquired to reach 1. The function is meant to be such that if the number of steps reaches the value 'max_steps'(without the algorithm reaching 1) it returns Nan. The code has to use a for loop and at least 1 if statement
N='Nan';
steps = 0;
while n~=1;
if mod(n,2) == 0;
n = n/2;
else
n = 3*n + 1;
end
steps=steps+1;
end
if steps>max_steps
disp=(N);
end
Most of the code is correct expect i cant seem to get 'Nan' when the number of steps reaches the value 'max_steps' and dont know i can implement a for loop
Any help will appreciated
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!