一個很有用的自定義函數(判斷自然數是否包含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開發資料庫,