Q8. Write a code to find whether a number is power of two or not
Power of Two :- we knoe that a power of two is a number of the form 2^n where n is an integer.
For Example :-
Input = 128
Output = 128 is the power of 2
So as we can see that 2^7 = 128. So the number 128 is the power of two.
Logic : Here we use a mathematical concept of Logarithm, The most simple method for finding whether a no 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.
There is Following 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
There is Following Code to find whether a number is power of two or notr
#include <stdio.h>
#include<stdbool.h>
#include<math.h>
/* Function to check if num is power of 2*/
bool find_power_of_two(int num) 
{ 
if(num==0) 
return false; 
return (ceil(log2(num)) == floor(log2(num))); 
} 
// Driver program 
int main() 
{ int num=128;
find_power_of_two(num)? printf(“%d is the power of two\n”,num): printf(“%d is not the power of two\n”,num); 
return 0; 
}
#include <bits/stdc++.h>
using namespace std; 
// Function to check if num is power of 2 
bool find_power_of_two(int num) 
{ 
if(num==0) 
return false; 
return (ceil(log2(num)) == floor(log2(num))); 
} 
// Driver program 
int main() 
{ int num=128;
find_power_of_two(num)? cout<< num<<” is the power of two”<< endl: cout<< num<<” is not the power of two”<< endl; 
return 0; 
}
class LFC 
{ 
/* Function to check if num is power of 2*/
static boolean find_power_of_two(int num) 
{ 
if(num==0) 
return false; 
return (int)(Math.ceil((Math.log(num) / Math.log(2)))) == 
(int)(Math.floor(((Math.log(num) / Math.log(2))))); 
} 
// Driver Code 
public static void main(String[] args) 
{ int num=128;
if(find_power_of_two(num)) 
System.out.printf(“%d is the power of two\n”,num); 
else
System.out.printf(“%d is not the power of two\n”,num); 
} 
}
import math 
# Function to check 
# Log base 2 
def Log2(x): 
if x == 0: 
return false; 
return (math.log10(x) / 
math.log10(2)); 
# Function to check 
# if x is power of 2 
def find_power_of_two(num): 
return (math.ceil(Log2(num)) == 
math.floor(Log2(num))); 
# Driver Code 
num=128
if(find_power_of_two(num)): 
print(“{0} is the power of two”.format(num)); 
else: 
print(“{0} is not the power of two”.format(num));
function Log2($x) 
{ 
return (log10($x) / 
log10(2)); 
} 
// Function to check 
// if x is power of 2 
function find_power_of_two($num) 
{ 
return (ceil(Log2($num)) == 
floor(Log2($num))); 
} 
// Driver Code 
$num=256;
if(find_power_of_two($num)) 
echo “$num is the power of two”; 
else
echo “$num is not the power of two”;
Output
128 is the power of two.
Recommended Programs
Program to find factorial of a number
Program to count number of digits in a number
