How would my script to show this in the command window?
Afficher commentaires plus anciens
My function is [s,m]=collatz(X). If I want s to equal the number of steps it takes for the number to equal one then how would I set it up? I know the idea is that the number of steps (s) increases by one every time the number goes through the while-loop. Then I need m to equal the maxvalue which comes from the biggest value in the list. Ex: >>[s,m]=collatz(3) s=7 m=16 since the list is 3-10-5-16-8-4-2-1
function[s,m]=collatz(x)
%This function will show the steps and maxvalue of even and odd natural
%numbers.It will show the show the number of steps it can repeat as long as
%the number is greater than one. It will show the maxvalue in the list
%Even numbers will be divided by 2
%Odd numbers will be multiplied by 3 and add to by one
%both will run as long as the result is greater than 1
clc
s=
m=
while x>1
if mod(x,2)==0 %shows x(natural number is even)
x=x/2
elseif mod(x,2)==1 %shows x(natural number is odd)
x=x*3+1
end
end
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
