Check if number belongs to the Fibonacci series using Memoization and recursion

”’

Created on Jun 17, 2015

@author: ishaansutaria

”’

#Using recursion

def checknumberBelongs(n):

    if n == 1 or n == 0:

        return n

    else:

        res = checknumberBelongs(n – 1) + checknumberBelongs(n – 2)

        print res

        return res

#Using memoization

memo = {0:0, 1:1}

def fibm(n):

    if not n in memo:

        memo[n] = fibm(n-1) + fibm(n-2)

        print memo[n]

    return memo[n]

fibm(5)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s