# Class notes for Wednesday, February 22, 2006

# This code continues the "3n+1" example from Monday's class.

# The countsteps function returns the number of steps required for a
# number n to reach 1

def countsteps(n):
    if n < 1:
        print "Sorry, n must be a positive number"
        return
    steps = 0
    while n > 1:
        if n % 2 == 0:
            n = n / 2
        else:
            n = 3 * n + 1
        steps = steps + 1
    return steps

# testnums illustrates the use of the break statement to break out of
# a loop when some condition is detected.  Beginning with 2, it tests
# each number in sequence to see how many steps that number requires
# to reach 1, keeping track of the current "champion" so far -- i.e.
# the number that takes the longest to reach 1.  Each time a new
# winner is found, a message is printed.

def testnums():
    n = 2
    currentChamp = 0
    currentChampSteps = 0
    while True:
        steps = countsteps(n)
        if steps > currentChampSteps:
            currentChamp = n
            currentChampSteps = steps
            print "A new winner! %d takes %d steps to reach 1" % (n, steps)
        n = n + 1
        # search only up to 500,000
        if n > 500000:
            break
    print "All done."

