• Courses
  • Tutorials
  • DSA
  • Data Science
  • Web Tech
August 21, 2024 |1.0K Views

Javascript program to find whether a number is power of two

  Share   Like
Description
Discussion

In this video, we will write a Javascript program to Check whether a Number is a Power of 2 or not. Basically, a power of two is a number of form 2n  where n is an integer.


Examples:
=> Input: n = 37
=> Output: No

=> Input: n = 16
=> Output: Yes

=> Input:n = 12
=> Output: n= No

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


1. Using ceil and floor function: In this method, we use math 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 division operator: 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.

3. By checking the count of the set bits: All power of two numbers has only a one-bit set. So count the number of set bits, and if you get 1 then the number is a power of two.

For example in binary:
2 = 10
4 = 100
8 = 1000

So the time and space complexity of all the methods are as follows:


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


2. Using division operator
Time Complexity: O(log2n)
Auxiliary Space: O(1)


3. By checking the count of set bits
Time complexity: O(N)
Auxiliary Space: O(1)

Javascript program to Check whether a Number is a Power of 2 or not : https://www.geeksforgeeks.org/javascript-program-to-check-whether-a-given-number-is-power-of-2/