Saturday, October 9, 2010

Fibonacci numbers built with SQL

I've been at work today and my friend Eugene has told me that he read somewhere about one guy who calculated Fibonacci numbers using SQL. He asked me to do the same... and after 5-10 minutes I've got the following query:
select N from (
       select @f0 N, @fn:=@f1+@f0, @f0:=@f1, @f1:=@fn 
       from   (select @f0:=0, @f1:=1, @fn:=1) x, 
       information_schema.COLUMNS p limit 10) y; 
The result is:
| 0 |
| 1 |
| 1 |
| 2 |
| 3 |
| 5 |
| 8 |
| 13 |
| 21 |
| 34 |
The length of sequence can be adjusted with the limit clause.
Or the same more friendly result in one line is:
select concat(group_concat(N),',...') from (
       select @f0 N, @fn:=@f1+@f0, @f0:=@f1, @f1:=@fn 
       from   (select @f0:=0, @f1:=1, @fn:=1) x, 
       information_schema.COLUMNS p limit 10) y; 
Than you should see:
| 0,1,1,2,3,5,8,13,21,34,... |
Instead of information_schema.COLUMNS table any table with many rows can be used.
Post a Comment
 
Blogged.com Technology Blogs