On 9/3/2013 9:57 PM, Ar wrote:
> How should I go about solving this.
>
> If n is even, divide it by 2 to get n/2.
> If n is odd, multiply it by 3 and add 1 to get 3n + 1.
>
> I have to write a function that will take any natural number as function input, apply
> the above rules and outputs the number iterations taken for that number to reduce to 1.
>
> Where the function starts as follows:
> function [iterations] = OddEven(x)
>
Just make sure to enter your name and date etc... below, I left
that blank

function k = OddEven(n)
%student name: <enter name>
%date: <enter date>
if round(n) ~= n  n<=0
if n<=0
error('input must be positive');
else
error('input must be integer');
end
end
k = 0;
while n ~= 1
if mod(n,2)
n = n*3 + 1;
else
n = n/2;
end
k = k + 1;
end
end

EDU>> k=OddEven(8)
3
EDU>> k=OddEven(19)
20
EDU>> k=OddEven(7)
16
Nasser
