【问题标题】:Postgres approach to solving Fibonacci sequencePostgres 解决斐波那契数列的方法
【发布时间】:2020-08-17 17:53:18
【问题描述】:

我正在尝试解决一个问题以使用 SQL 生成斐波那契数列。通过我的方法,查询在大约第 21 次迭代调用后通过一系列union all 对它的函数进行超时。

create function f(bigint) returns bigint
  as 'select case
        when $1 = 0 then 0
        when $1 = 1 then 1
        when $1 = 2 then 1
        when $1 = 3 then 2
      else f($1-1) + f($1-2)
      end;'
language sql
immutable
returns null on null input;

当前查询将 f(n) 生成为表中的行:

select f(0) as x
union all
select f(1) as x
union all
select f(2) as x
union all
...
select f(21) as x

generate_series(start, end)f(start),f(end) 可以以某种方式被利用吗?确实尝试过这种方法,但它似乎不起作用,因为它只是从头到尾返回结果,而不是斐波那契序列本身。

欢迎任何建议或替代方法。谢谢。

【问题讨论】:

  • 您是否尝试过在谷歌搜索“postgresql fibonacci”时发现的“示例”之一。第一个hit,第二个hit 可能不会超时....
  • 我确实尝试了一个类似于第一个链接的链接,但首先是为了我自己的角度。

标签: sql postgresql recursion


【解决方案1】:

和 Mike 一样,我的第一个想法是递归 CTE。但是,我将其表述为:

with recursive seed (n, fib_n, fib_n_minus_1) as (
       values (1::numeric, 1::numeric, 0::numeric)
      ),
      fib (n, fib_n, fib_n_minus_1) as (
       select n, fib_n, fib_n_minus_1
       from seed
       union all
       select n + 1, fib_n + fib_n_minus_1, fib_n
       from fib f
       where n < 1000
     )
select *
from fib
order by n;

【讨论】:

  • 谢谢,非常有用。我只需要将值转换为 bigint 即可正确显示。
猜你喜欢
  • 2010-10-12
  • 1970-01-01
  • 2015-06-05
  • 2020-01-18
  • 2014-11-28
  • 1970-01-01
  • 2019-05-10
相关资源
最近更新 更多