day1/exercise/find_pow_2.py
author Puneeth Chaganti <punchagan@fossee.in>
Thu, 09 Dec 2010 23:11:12 +0530
branchscipyin2010
changeset 448 dc8d666a594a
parent 64 333092b68926
permissions -rw-r--r--
Changed date format in day1/session{3,4,5}.tex.

def is_pow_2(n):
    bin_count = 0
    while n > 0:
        if n % 2 == 1:
            bin_count += 1
        if bin_count > 1:
            return False
        n /= 2

    return bin_count == 1

def collatz_pow_2(n):
    if n == 1: return 4
    if n == 2: return 4
    collatz_pow_2 = []
    while n > 2:
        print n, 
        if is_pow_2(n):
            collatz_pow_2.append(n)

        if n % 2:
            n = n * 3 - 1
        else:
            n /= 2 

    return max(collatz_pow_2)

import sys
collatz_pow_2(int(sys.argv[1]))