• Courses
  • Tutorials
  • Jobs
  • Practice
  • Contests
August 16, 2022 |2.6K Views
C Program to Find whether a Number is Power of 2
  Share   Like
Description
Discussion

In this video, we will write a C program to Check whether a Number is a Power of 2.

Basically, a power of two is a number of form 2^n where n is an integer.

In the video, to check whether a number is a power of 2 we will use two different methods:

1. Using ceil and floor function: In this method we use math.h ceil and floor functions. If the ceil and floor value of the input number is equal then the input number is the power of 2. Or we can say that If log2(n) is an integer then n is a power of 2, else not.

2. Using while loop: In this method, we keep dividing the input number by 2 iteratively and check whether n % 2 is not equal to zero and n is not equal to 1, which indicates n is not the power of 2 otherwise if n becomes 1 then it is the power of 2.

Examples :
Input: n = 37
Output: No

Input: n = 16
Output: Yes

Input:n = 12
Output: n= No

Apart from that, we will see the time and space complexity of both the methods,i.e

1. Using ceil and floor function
Time Complexity: O(1)
Space Complexity:(1)

2. Using while loop
Time Complexity: O(log2n)
Auxiliary Space: O(1)

C Program to find whether a no is power of two
https://www.geeksforgeeks.org/c-program-to-find-whether-a-no-is-power-of-two/

Read More