Fibonacci Rides Again

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 (11)
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

5 thoughts on “Fibonacci Rides Again

  1. Pingback: Fibonacci Rides Again… and Again « Pasha Golub's Blog
  2. Pingback: Factorial using CTE in PostgreSQL « Pasha Golub's Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s