Skip to content
Snippets Groups Projects
Commit 04bdb09e authored by Tobias Koelling's avatar Tobias Koelling
Browse files

fibonacci: hands-on session

parent 9fa1865f
No related branches found
No related tags found
1 merge request!24complexity lecture
...@@ -309,9 +309,16 @@ None ...@@ -309,9 +309,16 @@ None
## Fibonacci series example (3/3) ## Fibonacci series example (3/3)
$$ $$
\begin{pmatrix}f_{n-1}\\f_{n}\end{pmatrix} = \begin{pmatrix}0 & 1\\1 & 1\end{pmatrix} \begin{pmatrix}f_{n-2}\\f_{n-1}\end{pmatrix} \begin{pmatrix}f_{n}\\f_{n+1}\end{pmatrix} = \begin{pmatrix}0 & 1\\1 & 1\end{pmatrix} \begin{pmatrix}f_{n-1}\\f_{n}\end{pmatrix}
$$ $$
:::{.fragment}
$$
\begin{pmatrix}f_{n}\\f_{n+1}\end{pmatrix} = \begin{pmatrix}0 & 1\\1 & 1\end{pmatrix}^{n} \begin{pmatrix}f_0\\f_1\end{pmatrix}
$$
:::
## vector ## vector
```{python} ```{python}
...@@ -362,13 +369,16 @@ m * m * V2(0, 1) ...@@ -362,13 +369,16 @@ m * m * V2(0, 1)
## power function ## power function
```{python} ```{python}
#| echo: true #| echo: false
def power(a: "A", n: int, op: "A,A -> A, assoc" = lambda a, b: a * b): def power(a: "A", n: int, op: "A,A -> A, assoc" = lambda a, b: a * b):
assert n > 0 assert n > 0
if n == 1: return a if n == 1: return a
if n % 2 == 0: return power(op(a, a), n // 2, op) if n % 2 == 0: return power(op(a, a), n // 2, op)
return op(power(op(a, a), n // 2, op), a) return op(power(op(a, a), n // 2, op), a)
```
```{python}
#| echo: true
power(2, 4) power(2, 4)
``` ```
...@@ -380,6 +390,11 @@ power(m, 2) * V2(0, 1) ...@@ -380,6 +390,11 @@ power(m, 2) * V2(0, 1)
``` ```
::: :::
## Hands-on! {.handson}
* Implement that generic `power` function.
* Do so with a time complexity better than $\mathcal{O}(n)$
## fib3 ## fib3
```{python} ```{python}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment