File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 1+ CREATE OR REPLACE FUNCTION fibonacci (pstop int = 10 )
2+ RETURNS SETOF int
3+ LANGUAGE plpgsql IMMUTABLE STRICT AS
4+ $func$
5+ DECLARE
6+ a int := 0 ;
7+ b int := 1 ;
8+ BEGIN
9+ -- optional sanity check:
10+ -- function starts operating at 2
11+ -- and int4 computation overflows past Fibonacci Nr. 1836311903
12+ IF pstop NOT BETWEEN 2 AND 1836311903 THEN
13+ RAISE EXCEPTION ' Pass integer betwen 2 and 1836311903. Received %' , pstop;
14+ END IF;
15+
16+ RETURN NEXT 0 ;
17+ RETURN NEXT 1 ;
18+ LOOP
19+ a := a + b;
20+ EXIT WHEN a >= pstop;
21+ RETURN NEXT a;
22+
23+ b := b + a;
24+ EXIT WHEN b >= pstop;
25+ RETURN NEXT b;
26+ END LOOP;
27+ END;
28+ $func$;
29+ -- source: https://stackoverflow.com/questions/75588188/generating-fibonacci-sequence-with-pl-pgsql-function
30+
31+ comment on function fibonacci(pstop int) is ' Generates Fibonacci sequence' ;
32+
33+ -- TEST
34+ do $$
35+ begin
36+ assert (select count (* ) = 32 and sum (i) = 3524577
37+ from fibonacci(1346270 ) as t(i)
38+ );
39+ end;
40+ $$;
41+
You can’t perform that action at this time.
0 commit comments