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!