OraQA

Oracle Question and Answer

  • Do you have a solution to a problem? Do you have an unanswered question? Login and share it with the Oracle community. More...

Oracle News


Entries RSS feed

Comments RSS feed

How to compute the i-th Fibonacci number in SQL

September 9th, 2007 By Frank Zhou

The following is an interesting puzzle posted by Jsoftware: What are some ways of computing the i-th Fibonacci number?

———————SQL Solution——————-


SQL> variable input number;
SQL> exec :input  := 19;

SELECT initcap(lower(to_char(to_date(:input,'J'), 'JSPTH')))
       ||' Fibonacci number  : '||Fin_Fibonacci AS NUM
FROM
(SELECT Fin_Fibonacci
 FROM
(SELECT LEVEL n FROM dual CONNECT BY LEVEL <= :input)
 MODEL
 DIMENSION BY (n)
 MEASURES (CAST(NULL AS NUMBER) Fibonacci, count(*) over( ) as cnt,
           CAST(NULL AS NUMBER) Fin_Fibonacci)
 RULES ITERATE (1000000)
 UNTIL (ITERATION_NUMBER>= cnt[1]-1)
 (Fibonacci[ITERATION_NUMBER] ORDER BY n  =
  CASE WHEN ITERATION_NUMBER IN (0, 1)
       THEN ITERATION_NUMBER
	 ELSE Fibonacci[CV()-2] + Fibonacci[CV()-1]
       END,
  Fin_Fibonacci[ANY] ORDER BY n =
  CASE WHEN Fibonacci[CV()+1] IS NULL
       THEN Fibonacci[CV()]
  END
 )
)
WHERE Fin_Fibonacci IS NOT NULL;

NUM
---------------------------------------------------------
Nineteenth Fibonacci number  : 2584

Leave a Reply

You must be logged in to post a comment.

RSS feed for comments on this question