Sunday, 25 September 2016

Greatest common divisor using recursive method

By implementing the Euclidean algorithm, the greatest common divisor of any two numbers can be obtain through a recursive method.

Neat!


def gcdRecur(a, b):
    '''
    a, b: positive integers
    
    returns: a positive integer, the greatest common divisor of a & b.
    '''
    # Your code here
    if b>a: 
        tmp=a
        a=b
        b=tmp
    
    if (b==0):
        return a
    else:
        return gcdRecur(b, a%b)

Thursday, 22 September 2016

Greatest common divisor using iterative method

Another day, another python lesson on MITx.

This algorithm receive two integers and output the greatest common divisor of the integers.
It is implemented using iterative method.

Notice for future me: use and instead of the bitwise operator &.


def gcdIter(a, b):
    '''
    a, b: positive integers
    
    returns: a positive integer, the greatest common divisor of a & b.
    ''' 
    
    if(a>b):
        tmp=b
        while tmp>0:
            if (a%tmp==0 and b%tmp==0):
                return tmp
            else:
                tmp-=1        
        
    elif(b>a):
        tmp=a
        while tmp>0: 
            if (a%tmp==0 and b%tmp==0):
               return tmp
            else:
                tmp-=1


Shoutout to http://hilite.me/ for the source code formatting! Nifty little tool I will save for future usage.

Monday, 19 September 2016

Python: Specifications (docstring)

In writing Python codes, creator of the code/program is encourage to add a few lines of comments, also called docstrings, that describe what the code does, the input and the output.

Assumption: expected input from the user
Guarantees: here's what the function will do, given the proper input


def is_even(i):
 """
 Input: i, positive int
 Returns True if i is even, otherwise False
 """
      return i%2==0
          
is_even(3)