Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a1c3d52

Browse files
authored
Create negafibonacci_sequence.sql
1 parent 6935969 commit a1c3d52

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

‎functions/negafibonacci_sequence.sql‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
CREATE OR REPLACE FUNCTION public.negafibonacci_sequence(total int)
2+
returns setof int
3+
immutable
4+
strict -- returns null if any parameter is null
5+
parallel safe -- Postgres 10 or later
6+
security invoker
7+
language plpgsql
8+
set search_path = ''
9+
AS
10+
$func$
11+
DECLARE
12+
a int := 0;
13+
b int := 1;
14+
15+
i int := 2;
16+
min_total int := 3;
17+
max_total int := 47;
18+
BEGIN
19+
--inspired by: https://stackoverflow.com/questions/75588188/generating-fibonacci-sequence-with-pl-pgsql-function
20+
21+
IF total NOT BETWEEN min_total AND max_total THEN
22+
RAISE EXCEPTION 'First parameter betwen % and % expected, % given', min_total, max_total, total;
23+
END IF;
24+
25+
RETURN NEXT 0;
26+
RETURN NEXT 1;
27+
LOOP
28+
i := i + 1;
29+
a := a - b;
30+
RETURN NEXT a;
31+
EXIT WHEN i = total;
32+
33+
i := i + 1;
34+
b := b - a;
35+
RETURN NEXT b;
36+
EXIT WHEN i = total;
37+
END LOOP;
38+
END;
39+
$func$;
40+
41+
comment on function public.negafibonacci_sequence(total int) is $$
42+
Generates negative Fibonacci sequence.
43+
$$;
44+
45+
46+
--TEST
47+
do $$
48+
begin
49+
assert (select count(*) = 32 and sum(v) = 832041 and max(v) = 1346269
50+
from public.negafibonacci_sequence(32) with ordinality as t(v, o)
51+
);
52+
end;
53+
$$;
54+
55+
--select array(select public.negafibonacci_sequence(32));

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /