---
title: "算法概论 -- Chapter 0 Prologue"
author: "zbx_py"
date: "2014-10-15T12:02:21Z"
tags: ["Python", "算法"]
categories: ["编程语言"]
slug: "chapter-0-prologue"
draft: false
lastmod: "2014-10-15T12:00:55Z"
id: 2142691
url: "https://zbx-py.iteye.com/blog/2142691"
---

**Fibonacci numbers:**

 

***Introduction :***  
          ***F(n) = F(n-1) + F(n-2) , for n &gt;= 2,  and F(0) = 0,  F(1) = 1***  
          One approximation of F(n) is roughly ![](http://latex.codecogs.com/gif.latex?%7B%7B2%5E%7B0.694%7D%7D%7D), now I'm gonna prove it first.

 

          **Promble: Find a constant c &lt; 1 such that F(n) &lt;= ![](http://latex.codecogs.com/gif.latex?%7B%7B2%5E%7Bcn%7D%7D%7D) for all n &gt;= 0 , and find the minimal c.**

          proof :  We use induction to prove it and intuitively we can guess what is c. 

                      Suppose F(n) &lt;= **![](http://latex.codecogs.com/gif.latex?%7B%7B2%5E%7Bcn%7D%7D%7D) ,**  then we need to show F(n+1) &lt;= ![](http://latex.codecogs.com/gif.latex?%7B%7B2%5E%7Bc%28n%201%29%7D%7D%7D)  which means that ![](http://latex.codecogs.com/gif.latex?%7B%7B2%5E%7Bc%28n-1%29%7D%7D%7D) + **![](http://latex.codecogs.com/gif.latex?%7B%7B2%5E%7Bcn%7D%7D%7D) &lt;=** ![](http://latex.codecogs.com/gif.latex?%7B%7B2%5E%7Bc%28n%201%29%7D%7D%7D) . Solve this inequlity we get c &gt;= ![](http://latex.codecogs.com/gif.latex?%7B%5Clog%20_2%7D%28%5Cfrac%7B%7B1%20%20%20%5Csqrt%205%20%7D%7D%7B2%7D%29%20%5Capprox%200.694) , the following steps is simple, I'll leave it out.

 

          Then what does this approximation means? It means that the bit-length of F(n) is roughly 0.694n. So for a 32-bit machine, the word size is far less than F(n) , the arithmetic operation on F(n) cann't be considered as O(1) time given the bit-length.

 

        These are **three** ways to calculate Fibonacci:

 

        1. An exponential algorithm:

            

```
def fib1(n):
    """
    This function calculates fibonacci series.
    It takes exponential time.
    """
    
    if n <= 0 :
        return 0
    elif n == 1 :
        return 1
    else:
        return fib1(n-1) + fib1(n-2)
```

 

 

     Running time analysis: T(n) = T(n-1) + T(n-2) +  3 , for n &gt; 1. obviously T(n) &gt;= F(n) which grows exponentially.

 

       2. a Polynomial algorithm

       

```
def fib2(n):
    """
    This function calculates fibonacci series.
    It takes linear time.
    If n is too large, it takes roughly quadratic time.
    """
    if n == 0 :
        return 0
    res = []
    res.append(0)
    res.append(1)
    for i in range(2,n+1):
        res.append(res[i-1] + res[i-2])
    return res[n]
```

 

 

    Running time analysis: it's easy to see that it has reduced many redundant recurrences, the running time depends on the execution time of (res\[i-1] + res\[i-2]).

    if res\[i] is within machine word-length, it takes O(1) time, and the total time is O(n)

    But if res\[i] is beyond machine word-length, it takes O( ![](http://latex.codecogs.com/gif.latex?%7B%5Clog%20_2%7D%28F%28n%29%29) ) time and the total time is O(n* ![](http://latex.codecogs.com/gif.latex?%7B%5Clog%20_2%7D%28F%28n%29%29) )   = O( ![](http://latex.codecogs.com/gif.latex?n%5E2)) which is polynomial to n.

 

          3. A log time algorithm 

          

```
import numpy as np

def quick_power(a,n):
    """
    This function calculates a to the power of n.
    It takes log time. 未处理0的情况
    """
    if n == 1:
        return a
    elif n== 2:
        return a * a
    elif n % 2 == 0:
        temp_res = quick_power(a, n/2)
        return temp_res * temp_res
    else:
        temp_res = quick_power(a, (n-1)/2)
        return temp_res * temp_res * a
        

def fib3(n):
    """
    This function calculates fibonacci series.
    It takes log time.
    """
    origin = np.matrix([[1,1], [1,0]])
    res = quick_power(origin, n)
    
    return res[0, 1]
```

   

       Running time analysis:  This algorithm use an fact that : ![](http://latex.codecogs.com/gif.latex?%5Cleft%28%20%7B%5Cbegin%7Barray%7D%7B%2A%7B20%7D%7Bc%7D%7D%20%7B%7BF_%7Bn%20%20%201%7D%7D%7D&%7B%7BF_n%7D%7D%5C%5C%20%7B%7BF_n%7D%7D&%7B%7BF_%7Bn%20-%201%7D%7D%7D%20%5Cend%7Barray%7D%7D%20%5Cright%29=%20%7B%5Cleft%28%20%7B%5Cbegin%7Barray%7D%7B%2A%7B20%7D%7Bc%7D%7D%201&1%5C%5C%201&0%20%5Cend%7Barray%7D%7D%20%5Cright%29%5En%7D)

       We use quick\_power to do n-power operation for O(log n) time, but there are some problem in it. We do 8 mulplications in matrix mulplication rather than simple addition. As you know, multiplication may take more time than addition, so when n is large ,  it needs further analysis.  This part isn't completed.

 

       Finally this is the running result of above 3 algorithms: Red : fib1 ,  blue : fib2,  grenn : fib3 , y-axis: time, x-axis : n. 

 

         
![](http://dl2.iteye.com/upload/attachment/0101/9883/68c8e94c-0f26-3993-9cd5-6df3eac002e4.png)  
 

 

       

1. \[list=1]\[list=1]\[list=1]

\[/list]

\[/list]

\[/list]