在T-SQL中创建递归存储过程以计算第n个Fibonacci数

时间:2014-03-19 23:23:47

标签: sql tsql sql-server-2012

我在转让中提出了以下问题。我无法理解如何在存储过程中传递参数。 奎斯顿:

If n = 1, FibNum(a, b, n) = a  If n = 2, FibNum(a, b, n) = b If n > 2, FibNum(a, b, n) = FibNum(a, b, n-1) + FibNum(a, b, n-2) a

在T-SQL 中创建递归存储过程FibNum以计算第n个Fibonacci数,给出以下过程声明 CREATE PROC FibNum(@a int,@ b int,@ n int)其退出代码是第n个斐波纳契数。 湾利用存储过程计算FibNum(1,1,10)的结果。附上截图。

4 个答案:

答案 0 :(得分:0)

这似乎是一个函数问题,但不是因为递归存储过程。你实际上可以使用递归CTE来做到这一点。

这样做的自然方式如下:

with fib as (
      select 1 as i, 0 as n
      union all
      select 2 as i, 1 as n
      union all
      select f1.i + 1, f1.n + f2.n2
      from fib f1 join
           fib f2
      where i < 10
     )
select *
from fib;

但是你不能这样做,因为你不能在from条款中两次引用CTE。

相反,您希望将前两个值放在一行中:

with fib as (
      select 1 as i, 1 as n, 0 as n1
      union all
      select f.i + 1, f.n + f.n1, f.n
      from fib f
      where i < 10
     )
select *
from fib;

如果您想要第n个,只需将10更改为您想要的数字,然后使用select top 1 order by使用{{1}}。

答案 1 :(得分:0)

程序

create proc FibNum ( @a int, @b int, @n int )
as begin
  if @n = 1 return @a
  if @n = 2 return @b
  if @n > 2 begin
    declare @n1 int = @n - 1, @n2 int = @n - 2, @R1 int, @R2 int
    exec @R1 = FibNum @a,@b,@n1
    exec @R2 = FibNum @a,@b,@n2
    return @R1 + @R2
  end
  return 1
end

利用率:

declare @R int
exec @R =  FibNum 1,1,10
select @R

答案 2 :(得分:0)

不能看到@a和@b的需要,只需参数n即可实现递归的fib(n)

CREATE PROC FibNum (@n INT)
AS
BEGIN
    DECLARE @nminus1 INT, @nminus2 INT, @f1 INT, @f2 INT
    IF @n < 2
        RETURN @n
    ELSE
        SET @nminus1 = @n - 1 
        SET @nminus2 = @n - 2
        EXEC @f1 = FibNum @nminus1
        EXEC @f2 = FibNum @nminus2
        RETURN @f1 + @f2
END

答案 3 :(得分:0)

我必须为作业写这个,并认为我可以在这里发布。

DECLARE @F0 BIGINT = 0
DECLARE @F1 BIGINT = 1
DECLARE @COUNTER BIGINT = 0
DECLARE @INTERIM BIGINT

WHILE @COUNTER < 1000

BEGIN 
    IF @F0 = 0  AND @F1 = 1
        BEGIN
            SELECT @F0 AS 'Fibo' INTO #fibonacci
            INSERT INTO #fibonacci SELECT @F1
            INSERT INTO #fibonacci SELECT @F0 + @F1
            SET @INTERIM = @F0 + @F1
            SET @F0 = @F1
            SET @F1 = @INTERIM
            SET @COUNTER += 1
        END
    ELSE
        BEGIN
            INSERT INTO #fibonacci SELECT @F0 + @F1
            SET @INTERIM = @F0 + @F1
            SET @F0 = @F1
            SET @F1 = @INTERIM
            SET @COUNTER += 1
        END
END
SELECT * FROM #fibonacci