How to determine whether a number is 2 n power

Source: Internet
Author: User
Given an integer num, determine whether the integer is the n power of 2. For example, 2, 4, and 8 are the power of 2, and 6 and 10 are not the power of N2. Therefore, I think the most safe thing is bitwise calculation. it depends on the number of 1, which is the most practical. Of course, there is a negative number here. The first is 1, and the remaining is 0. However, a clever reviewer provides a very powerful method to avoid negative use cases: the parameter type is uint!

Question: Given an integer num, determine whether the integer is the Npower of 2. For example, 2, 4, and 8 are the power of 2, and 6 and 10 are not the power of N2.

See the following program:

public static bool Check1(int num){    int i = 1;    while (true)    {        if (i > num)            return false;        if (i == num)            return true;        i = i * 2;    }}

Continuously loop num % 2. if it is not equal to 0, return false, if it is equal to 0, num = num/2, always achieve num = 1

public static bool Check2(int num){    if (num == 1)        return true;    else    {        do        {            if (num % 2 == 0)                num = num / 2;            else                return false;        }        while (num != 1);        return true;    }}

In fact, the two algorithms share the same idea, but the second one is more efficient than the first one, because if it is not the Npower of 2, it can be cyclically reduced many times!

Because the number of n 2 binary represents 1st bits for 1, the rest is 0, and the X-1 (if x is the n 2) the binary representation of the obtained number is exactly 0 for 1st bits and 1 for the rest. The result is 0, otherwise the result is certainly not 0.

public static boolean getResult(int num) { if (num <= 1)     { return false; }     else     { return ((num & (num - 1)) == 0) ? true : false; } } public static void main(String[] args) { System.out.println(getResult(32)); } 

The above Program judges another one. we know that 1 is the power 0 of 2. 1 should meet the requirements. The following corrections:

public static bool floor_7(int num)    {        if (num <= 1)        {            return false;        }        else        {            return ((num & (num - 1)) == 0) ? true : false;        }    }

If a number is an integer power of 2, the result is as follows: 010000 ....

In addition to the zero side of 2, that is, 1, this number is reduced for a moment to get: 001111 ....

In other words, we can get a number with all the values above 0 and all the values below 1. make a bitwise sum between the number and the original number and get: 000000 .....

In other words, if a number n is not 1 and n-1 & n = 0, n is an integer power of 2. As long as there are two 1 s in the binary expression, this rule will not be satisfied. Therefore, the simplest judgment method is:

if ( n < 0 )throw new InvalidOperationException();if ( n < 2 )return false;return n & ( n - 1 ) == 0

After correction:

public bool floor_8(int n)    {        if (n < 0)            throw new InvalidOperationException();        if (n < 2)            return false;        return n & (n - 1) == 0;    }

Logarithm algorithm:

bool foo(int x){    float ret = log(x)/log(2);     return abs((int) ret - ret) <= 0.00001;}

After correction:

public bool floor_22(int x)    {        float ret = log(x) / log(2);        return abs((int)ret - ret) <= 0.00001;    }

The logarithm algorithm is interesting. Unfortunately, the floating point error is not an easy problem to avoid. Because floating point numbers cannot be directly compared, a 0.00001 scale is used. So there is a problem: what happens when x is large? I found an abnormal number to test: 0x10000001

The result is true. Because the decimal part of the result is too small.

static void Main(string[] args){int i = int.Parse(Console.ReadLine());Console.WriteLine(IsCheck(i));}public static bool IsCheck(int num){double result = Math.Log(num, 2);if (result.ToString().IndexOf(".") >= 0){return false;}else{return true;}}

The same problem. If LOG is used, the loss of precision of floating point numbers cannot be avoided. This is impossible.

public static bool floor_37(int num)    {        double result = Math.Log(num, 2);        if (result.ToString().IndexOf(".") >= 0)        {            return false;        }        else        {            return true;        }    }

So I have summarized the (x) & (x-1) algorithm has not been proved, I do not know there is no other inverse examples except 0. After all, this formula does not strictly prove the process.

Therefore, I think the most safe thing is bitwise calculation. it depends on the number of 1, which is the most practical. Of course, there is a negative number here. The first is 1, and the remaining is 0. However, a clever reviewer provides a very powerful method to avoid negative use cases: the parameter type is uint!

Okay, you won.

Address of this article: http://www.nowamagic.net/librarys/veda/detail/1031,welcome.

Related Article

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.