|
Revision 323, 0.7 kB
(checked in by simon, 4 years ago)
|
|
O(log n) calculation of the n'th Fibonacci number.
|
-
Property svn:mime-type set to
text/python-source
-
Property svn:eol-style set to
native
|
| Line | |
|---|
| 1 | #!/usr/bin/env python |
|---|
| 2 | |
|---|
| 3 | import numpy |
|---|
| 4 | |
|---|
| 5 | def fib(n): |
|---|
| 6 | """Calculate the n'th Fibonacci number in O(log n) time. |
|---|
| 7 | |
|---|
| 8 | The method used is described at: |
|---|
| 9 | http://davmac.org/davpage/algrthm/fibonacci.html |
|---|
| 10 | and uses |
|---|
| 11 | | 0 1 |^n == | fib(n-1) fib(n) | |
|---|
| 12 | | 1 1 | | fib(n) fib(n+1) | |
|---|
| 13 | It breaks the n matrix muliplications by dividing n by 2 |
|---|
| 14 | contintually in order to build up the n'th power. |
|---|
| 15 | """ |
|---|
| 16 | a = numpy.matrix([[0, 1], [1, 1]]) |
|---|
| 17 | x = numpy.matrix([[1, 0], [0, 1]]) |
|---|
| 18 | while n > 0: |
|---|
| 19 | if n % 2 == 1: |
|---|
| 20 | x = x*a |
|---|
| 21 | a = a**2 |
|---|
| 22 | n = n >> 1 |
|---|
| 23 | return x[0,1] |
|---|
| 24 | |
|---|
| 25 | |
|---|
| 26 | if __name__ == "__main__": |
|---|
| 27 | for n in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]: |
|---|
| 28 | print n, ":", fib(n) |
|---|