Parallelize Fibonacci sequence generator

﹥>﹥吖頭↗ 提交于 2020-01-01 10:47:19

问题


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?


回答1:


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).




回答2:


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

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

or you can go with other mathematical way, such as




回答3:


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.



来源:https://stackoverflow.com/questions/16464498/parallelize-fibonacci-sequence-generator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!