Jump to content

User:Kithira/Course Pages/CSCI 12/Assignment 2/Group 5/Homework 2

From Wikipedia, the free encyclopedia

Below was our favorite solution to one of the Lab 2 problems, a solution to the problem of finding the Syracuse number.

def Syracuse (n):

edit = 3*n + 1
while (edit%2) == 0:
edit = edit >> 1
return edit

def _test():

assert(Syracuse(3)==5)
assert(Syracuse(5)==1)
assert(Syracuse(7)==11)

if __name__=='__main__':

_test()


This program takes an odd number n, and first calculates (3*n+1), which it associates with the variable name "edit". There is then a while loop that executes as long as "edit" modulo 2 is 0, which is a test to see that "edit" is even. As long as that is true, the loop divides edit by two, using a clever bitshift right of one, which we can do because we are dividing by a power of two. This is the algorithmic way to find the Syracuse number.


Comments

[edit]

This code uses the bitshift operator to its advantage, saving CPU runtime as bitshifts are much more faster than division as computers operate in base 2. However, the purpose of this function is a little confusing. Is the function's purpose to calculate the syracuse number of a given number? If so, why should the input value be limited to odd numbers; even numbers should be able to be read in as well. This is necessary if this function were to calculate a hailstone sequence of a number; if the purpose is just to simulate the syracuse function (which is slightly different than a syracuse number), then the code works just fine. Otherwise, the code itself is presented clearly and analyzed articulately.