Given an integer n, find whether it is a power of d or not, where d is itself a power of 2.
Input : n = 256, d = 16 Output : Yes Input : n = 32, d = 16 Output : No
Method 1 Take log of the given number on base d, and if we get an integer then number is power of d.
Method 2 Keep dividing the number by d, i.e, do n = n/d iteratively. In any iteration, if n%d becomes non-zero and n is not 1 then n is not a power of d, otherwise n is a power of d.
A number n is a power of d if following conditions are met.
a) There is only one bit set in the binary representation of n (Note : d is a power of 2)
b) The count of zero bits before the (only) set bit is a multiple of log2(d).
For example: For n = 16 (10000) and d = 4, 16 is a power of 4 because there is only one bit set and count of 0s before the set bit is 4 which is a multiple of log2(4).
64 is a power of 8
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Check if a number is power of 8 or not
- Given a HUGE number check if it's a power of two.
- Check if a number can be expressed as power | Set 2 (Using Log)
- Check whether a given Number is Power-Isolated or not
- Check if a number can be expressed as x^y (x raised to power y)
- Check if a number is power of k using base changing method
- Check if the number is a Prime power number
- Find the sum of power of bit count raised to the power B
- Check if a number is a power of another number
- Compute power of power k times % m
- Find power of power under mod of a prime
- Check if any permutation of N equals any power of K
- Check if bitwise AND of any subset is power of two
- Check if n is divisible by power of 2 without using arithmetic operators
- Sum of digits of a given number to a given power
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.