Algorithm and Flowchart to find the power of 2

[407 views]


Flowchart to find the power of 2:

Algorithm and flowchart to find the power of 2
Remove WaterMark from Above Flowchart

Algorithm for power of 2:

Declare n and count Read n if(n&n-1 ==0 and n!=0) { count=log(n)/log(2); } print(count)

In this program we declare two integers, one for taking input and other for storing the result and giving output. We read n and if(n&(n-1))==0 and n not equal zero, then it will enter the loop.

Let us understand this n&(n-1) and integer which is power of 2 in the binary numbers it will be 1,10,100,1000,10000 which in decimal system is 0,2,4,8,16. That number subtracting it by 1 will give 0,01,011,0111,01111 which is totally opposite of numbers which are power of 2. If we take bitwise and operator for that i.e. n&(n-1) it will always give you zero for the number which are power of 2. So through this we can understand whether the number is power of 2 or not.

Once we get to know the number is power of 2 with the help of log formula ( log2 (x) = logy (x) / logy (2)) we find the log2(n) and print the result.

Program for Finding Power of 2 in C:

#include<stdio.h> #include<math.h> int main() { int n, count; printf("Enter number:"); scanf("%d", & n); if ((n & (n - 1)) == 0 and n != 0) { count = log(n) / log(2); } printf("power of 2 is %d", count); }

Output of Program:

C Program to find the power of 2
        

Struggling to Understand Algorithm and Flowchart? Try our Notes



Want to Test Your Knowledge on Algorithm and Flowchart?



Comments



Search
Recommended Deals End in

Top Java Interview Questions PDF Guide with 30+ Pages



Online Games
Play 2048 Game Online and Relax.
Play 2048 Game Online

Quiz to Test Your Skills
Search Tags

    Algorithm to find the power of 2

    Flowchart to find the power of 2

    Write a Pseudocode to Find Power of 2

    C Program to find power of 2