Parallelize Fibonacci sequence generator

落爺英雄遲暮 提交于 2019-12-04 06:55:52

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

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

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.

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