How do you check if an integer is a power to another integer in python?
Python Challenges - 1: Exercise-5 with SolutionWrite a Python program to check if an integer is the power of another integer. Show Explanation: Sample Solution:- Python Code:
Sample Output: True False True Flowchart: Visualize Python code execution:The following tool visualize what the computer is doing step-by-step as it executes the said program: Python Code Editor: Contribute your code and comments through Disqus. Previous: Write a Python program to check if a number is a perfect square. Given two positive numbers x and y, check if y is a power of x or not. Input: x = 10, y = 1 Output: True x^0 = 1 Input: x = 10, y = 1000 Output: True x^3 = 1 Input: x = 10, y = 1001 Output: False A simple solution is to repeatedly compute powers of x. If a power becomes equal to y, then y is a power, else not. C++
Java
Python3
C#
PHP
Javascript
Output: 1 0 1 0 Time complexity of above solution is O(Logxy) 1) Initialize pow = x, i = 1 2) while (pow < y) { pow = pow*pow i *= 2 } 3) If pow == y return true; 4) Else construct an array of powers from x^i to x^(i/2) 5) Binary Search for y in array constructed in step 4. If not found, return false. Else return true. Alternate Solution : C++
Java
Python3
C#
PHP
Javascript
Output : 1 Thanks to Gyayak Jain for suggesting this solution. How do you check if a number is a power of another Python?1) Initialize pow = x, i = 1 2) while (pow < y) { pow = pow*pow i *= 2 } 3) If pow == y return true; 4) Else construct an array of powers from x^i to x^(i/2) 5) Binary Search for y in array constructed in step 4. If not found, return false.
How do you check if an integer is a power of 2 in Python?A simple method for this is to simply take the log of the number on base 2 and if you get an integer then number is power of 2.. Another solution is to keep dividing the number by two, i.e, do n = n/2 iteratively. ... . All power of two numbers have only one bit set.. How do you evaluate a power in Python?Python pow() Function
The pow() function returns the value of x to the power of y (xy). If a third parameter is present, it returns x to the power of y, modulus z.
|