
% Homework 2 Solutions
% smallest.m
% CS 1109, Summer 2011
% July 13

% This script computes the smallest number whose ``up-down'' sequence
% consists of at least 500 steps. It adapts the code that was written in
% updown.m

clc
clear

number = 2;
numSteps = 0;

% Repeat while we have not found a number with at least a 500-step
% ``up-down'' sequence
while (numSteps < 500)
    
    numSteps = 0;
    originalNumber = number;
    
    % Until we hit 1, repeat the following step: if number is even, halve
    % it. If it is odd, replace it with 3*number + 1. Keep track of how
    % many times we have to perform this operation in numSteps.
    while (number > 1)
        
        if (rem(number, 2) == 0)
            number = number / 2;
        else
            number = 3*number + 1;
        end
    
        numSteps = numSteps + 1;
    end
    
    % Try the next integer
    number = originalNumber + 1;
end

% Print results
fprintf('The smallest number with at least 500 steps');
fprintf(' in its up-down sequence is %d\n', originalNumber);

% Common mistakes / other observations:
%
% 1) Most people successfully solved this problem. Those who did lose 
% points did so for failing to adhere to the code standards
% -- for example, missing comments, not indenting code properly etc.
% Remember to go through the checklist in the problem handout before you
% submit solutions!
%
% 2) Observe how the fprintf statements at the end of this problem were
% split up across two lines. Remember --- fprintf does *not* print a new
% line unless you explicitly use a `\n'. This is useful for when you want
% to print a long message, but want to break it up across multiple lines
% for better readability like here.

