SQL实现杨辉三角

 
  1. create proc pr_YangHui
  2.     @n int  --杨辉三角的层数,1~67
  3. as
  4. begin
  5.     set nocount on
  6.     if @n<1 or @n>67 
  7.         return
  8.     declare @t table(nid int identity(1,1), val bigint) --存储杨辉三角中的数字
  9.     insert @t select top 80 1 from sysobjects a, sysobjects b
  10.     declare @i int, @str varchar(4000), @nWidth int, @cSpace varchar(20)
  11.     
  12.     --计算数字的最大宽度,以便控制数字前面显示的空格
  13.     set @i=1
  14.     while @i<=@n
  15.     begin
  16.         update a set val=a.val+b.val
  17.         from @t a join @t b on a.nid=b.nid+1 where a.nid<@i         
  18.         set @i=@i+1     
  19.     end     
  20.     select @nWidth = len(max(val))+1 from @t    
  21.     update @t set val=1 where nid<@i
  22.     select @nWidth = @nWidth + @nWidth%2, @cSpace=space(@nWidth)
  23.     --打印杨辉三角
  24.     set @i=1
  25.     while @i<=@n
  26.     begin
  27.         update a set val=a.val+b.val
  28.         from @t a join @t b on a.nid=b.nid+1 where a.nid<@i
  29.         set @str=''
  30.         select @str=@str+right(@cSpace+cast(val as varchar), @nWidth) from @t where nid<=@i
  31.         print space((@n-@i)*@nWidth/2)+@str
  32.         set @i=@i+1     
  33.     end 
  34. end
  35. go
  36. exec pr_YangHui 6
  37. /*
  38.              1
  39.            1   1
  40.          1   2   1
  41.        1   3   3   1
  42.      1   4   6   4   1
  43.    1   5  10  10   5   1
  44. */
  45. --drop proc pr_YangHui
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值