Not so long ago I wrote about implementing GCD function in PostgreSQL using CTE.
Here I will show how Fibonacci Numbers may be obtained using the same technique.
So to have first 16 members of this sequence we should execute something like this:
WITH RECURSIVE t(a, b) AS ( VALUES (1, 1) UNION ALL SELECT b, a + b FROM t ) SELECT a FROM t LIMIT 16; |
Suppose we should add this code to Wiki Library Snippets. Any objections? 😉
UPD. Some others unnatural ways to calculate Fibonacci numbers may be found in Russian.
Advertisements
Should it be “VALUES (1, 2)” instead of “VALUES (1, 1)”?
LikeLike
By definition, the first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum of the previous two. Some sources omit the initial 0, instead beginning the sequence with two 1s.
LikeLike
Yeah, after searching a while I found the same answer. Thanks and sorry. 🙂
LikeLike