Code covered by the BSD License  

Highlights from
Collatz

from Collatz by Matt Fig
Tools for examining the Collatz sequence.

collatz(n)
function [Sequence, Number_of_Elements] = collatz(n)
%COLLATZ(n) Returns the collatz sequence for n.
% Also can give the number of elements
% in the sequence.
% Usage: [Sequence, Number_of_Elements] =collatz(n)
% Author:  Matt Fig  Montana State University
% Contact:  popkenai@yahoo.com

g(1) = n;   kk = 1;
while g(kk)>1
      if odd(g(kk))
         g(kk+1) = 3*g(kk)+1;
      else
         g(kk+1) = .5*g(kk);
      end
      kk=kk+1;        
end
Sequence = g';   Number_of_Elements = length(g);

function val = odd(jj)
val = rem(jj,2);

Contact us at files@mathworks.com