Parallelize Fibonacci sequence generator

2019-04-08 07:35发布

I'm learning about parallelization and in one exercise I'm given a couple of algorithms that I should improve in performance. One of them is a Fibonacci sequence generator:

array[0] = 0;
array[1] = 1;
for (q = 2; q < MAX; q++) {
    array[q] = array[q−1] + array[q−2];
}

My suspicion is, that this cannot be optimized (by parallelization), since every number depends on the two preceding numbers (and therefore indirectly on all preceding numbers). How could this be parallelized?

3条回答
唯我独甜
2楼-- · 2019-04-08 07:42

The best way to approach it to use 2-dimensional matrix form of Fibonacci

enter image description here

Now you can easily expand it. Simple matrix multiplication concepts will do it.

or you can go with other mathematical way, such as

enter image description here

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-04-08 07:44

The Fibonacci sequence is determined just by its first two elements; in fact, you could somehow parallelize it, although ugly:

F(n + 2) = F(n + 1) + F(n)
F(n + 3) = F(n + 1) + F(n + 2) = F(n + 1) * 2 + F(n)
F(n + 4) = F(n + 2) + F(n + 3) = F(n + 1) * 3 + F(n) * 2
F(n + 5) = F(n + 3) + F(n + 4) = F(n + 1) * 5 + F(n) * 3
F(n + 6) = F(n + 4) + F(n + 5) = F(n + 1) * 8 + F(n) * 5

Hopefully by now, you can see that:

F(n + k) = F(n + 1) * F(K) + F(n) * F(k - 1)

So after computing the first k numbers, you could use this relation to compute the next k items in the sequence, at the same time, parallelized.

You could also use the direct formula for Fibonacci numbers to compute them in parallel, but that is kind of too uncool (also might be too simple for learning purposes that it might serve).

查看更多
淡お忘
4楼-- · 2019-04-08 08:04

A number 'n' is a Fibanocci number if either (5n^2 - 4) or (5n^2 + 4) is a perfect square.

http://en.wikipedia.org/wiki/Fibonacci_number

So given a large number, you can find the next two Fib nums using this algorithm and continue with your addition then onwards.

In that way, you could partition the problem as between (0 to N/2) and then (N/2 + 1 to N) and run it in parallel threads.

查看更多
登录 后发表回答