Collatz Conjecture using for loop
Show older comments
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
Accepted Answer
More Answers (0)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!