Can anyone help with this fibosum problem in SPOJ. I tried it with normal method by storing the fibonacci numbers in array and finding the sum. http://www.spoj.com/problems/FIBOSUM/
| # | User | Rating |
|---|---|---|
| 1 | Benq | 3792 |
| 2 | VivaciousAubergine | 3647 |
| 3 | Kevin114514 | 3603 |
| 4 | jiangly | 3583 |
| 5 | turmax | 3559 |
| 6 | tourist | 3541 |
| 7 | strapple | 3515 |
| 8 | ksun48 | 3461 |
| 9 | dXqwq | 3436 |
| 10 | Otomachi_Una | 3413 |
| # | User | Contrib. |
|---|---|---|
| 1 | Qingyu | 157 |
| 2 | adamant | 153 |
| 3 | Um_nik | 147 |
| 4 | Proof_by_QED | 146 |
| 5 | Dominater069 | 145 |
| 6 | errorgorn | 142 |
| 7 | cry | 139 |
| 8 | YuukiS | 135 |
| 9 | TheScrasse | 134 |
| 10 | chromate00 | 133 |
Can anyone help with this fibosum problem in SPOJ. I tried it with normal method by storing the fibonacci numbers in array and finding the sum. http://www.spoj.com/problems/FIBOSUM/
| Name |
|---|



Well, your method isn't normal because the constrains are too big.
I think this problem can be solved using binary exponentiation of a matrix.
At first, sorry for my english.
Let 's call S(n) = FIB(1) + FIB(2) + ... + FIB(n)
It is easy to calculate S(n), DIY (Hint: try calculate S(1), S(2), S(3), S(4) by hand (or computer, whatever), you should find a very simple formula)
The rest is easy. O(lg (max(m, n))
If you lazy: http://www.wolframalpha.com/input/?i=Sum+Fib%28n%29
It's clear that we only need the sum of the first n Fibonacci numbers. As we know that
with $F_0=F_1=1$, the sum of all Fibonacci numbers from 0-th to n-th will be just a geometric series:
where $E$ is the 2x2 unit matrix and division by matrix A - E can be replaced by multiplication by the inverse of that (non-singular) matrix, which is
so in this particular case (Fibonacci numbers),
and using modular exponentiation of matrices, the result can be computed in $O(\log{N})$ time.
Alternatively, you could use a modular inverse matrix:
, it requires less knowledge about matrices.
There's a nice identity that you can prove by induction or by telescoping sums: F0 + F1 + ... + Fn = Fn + 2 - 1. This way, you only have to calculate two fibonacci numbers per query and this can be done with matrix exponentiation as everyone else said.