首页 > 开发 > 综合 > 正文

一个很有用的自定义函数(判断自然数是否包含2的指定次幂)

2024-07-21 02:05:39
字体:
来源:转载
供稿:网友

/*           name :    fun_wheincluded           function :   判断选定的数字是否在给定的整数中           可以知道任何一个自然数都可以拆分成若干个2的幂的和,如:                1 = 2^0                2 = 2^1                3 = 2^0 + 2^1                4 = 2^2                5 = 2^0 + 2^2                6 = 2^1 + 2^4                7 = 2^0 + 2^1 + 2^2                8 = 2^3                9 = 2^0 + 2^3                10 = 2^1 + 2^3                11 = 2^0 + 2^1 + 2^3                12 = 2^2 + 2^3                13 = 2^0 + 2^2 + 2^3                14 = 2^1 + 2^2 + 2^3                15 = 2^0 + 2^1 + 2^2 + 2^3                16 = 2^4                17 = 2^0 + 2^4         将任意一个数解析为2的幂的和的方法——递归    规律:                如给定 14                  ∵ 2^3 < 14 < 2^4                  ∴ 14中必有8——2^3                  14 - 8 = 6                  ∵ 2^2 < 6 < 2^3                  ∴ 6中必有4——2^2                  6 - 4 = 2                         ∵ 2 = 2                  ∴ 14 = 2^3 + 2^2 + 2^1

            parameters :  @totalnum           type:   int           @specifiednum             type:   int            steps :                author :   waxdoll cheung            date :    2005-03-21*/

create function  dbo.fun_wheincluded (  @totalnum int,   @specifiednum int )returns bit as  begin

 declare @varret bit

 declare @varloop int

 set @varloop = 0

 while (@totalnum >= cast(power(2, @varloop) as int))  set @varloop = @varloop + 1

 set @totalnum = @totalnum - cast(power(2, @varloop - 1) as int)

 if (@varloop = @specifiednum + 1)  set @varret = 1 else begin  if (@totalnum >= 1)   return dbo.fun_wheincluded(@totalnum, @specifiednum)  else   set @varret = 0 end

 return @varretend
注册会员,创建你的web开发资料库,
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表