Q. C# program to find whether a number is power of two or not.

Here you will find an algorithm and program in C# programming language to find whether the given number is power of 2 or not. Now first let us understand what power of two means.

Explanation : In mathematics, a power of two is a number of the form 2^n where n is an integer. Here we use a mathematical concept of Logarithm, The most simple method for finding whether a number is power of two or not is to simply take the log of the number on base 2 and if you get an integer then the number is the power of 2.

For Example : 256, when we take log of 256 to the base 2 we get 8 which is integer, hence 256 is power of 2.

Algorithm to find whether a number is power of two or not

START
Step 1 → Take integer variable num
Step 2 → find out the log number with base 2
Step 3 → if outcome is integer then DISPLAY number is power of 2.
Step 4 → Otherwise, DISPLAY number is not power of 2.
STOP


C# Program to Find Whether a Given Number is Power of 2

using System; 
class LFC 
{ 
    static bool find_power_of_two(int num) 
    { 
        if(num==0) 
            return false; 
        return (int)(Math.Ceiling((Math.Log(num) /  
        Math.Log(2)))) == 
        (int)(Math.Floor(((Math.Log(num) /  
        Math.Log(2))))); 
    } 

    public static void Main() 
    {   
        int num=256;
        if(find_power_of_two(num)) 
            Console.WriteLine("{0} is the power of two",num); 
        else
            Console.WriteLine("{0} is not the power of two",num); 
    } 
} 

Output

256 is the power of two.