A useful User-Defined Function (determining whether a natural number contains a specified power of 2)

Source: Internet
Author: User

/*

Name: fun_whesponded

Function: determines whether the selected number is in the given integer.

We can know that any natural number can be split into several 2's power and, for example:

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



Method for resolving any number to the sum of the power of 2-recursion

Rule:

If 14

Limit 2 ^ 3 <14 <2 ^ 4

There must be 8-2 ^ 3 in limit 14

14-8 = 6

Limit 2 ^ 2 <6 <2 ^ 3

IPv6 must have 4--2 ^ 2

6-4 = 2



Limit 2 = 2

Limit 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_whesponded

(

@ Totalnum int,

@ Specifiednum int

)

Returns bit

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_whesponded (@ totalnum, @ specifiednum)

Else

Set @ varret = 0

End

Return @ varret

End

It can be used in many places to see if you can think of it ......

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.