A very useful custom function (to determine whether a natural number contains a specified power of 2)

Source: Internet
Author: User
Tags contains return
Function
/*           Name:    Fun_WheIncluded            function:    Determine whether the selected number is in the given integer              can know that any natural number can be split into a number of 2 powers and, such as:                 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           a method that resolves any number to a power sum of 2--recursive      law:                  as given  14                   ∵ 2^3 < < 2^4                 There must be 8--2^3              in the   ∴ 14.       14-8 = 6                   ∵ 2^2 < 6 < 2^3             There must be 4--2^2          in the       ∴ 6.          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*/

The 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 to dbo. Fun_wheincluded (@TotalNum, @SpecifiedNum) ELSE SET @varRet = 0 End

Return @varRetEND


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.