Write a python program to check if a number is a power of a given base

Last update on August 19 2022 21:50:48 [UTC/GMT +8 hours]

Python Challenges - 1: Exercise-6 with Solution

Write a Python program to check if a number is a power of a given base.

Sample Solution:-

Python Code:

import math

def isPower [n, base]:
    if base == 1 and n != 1:
        return False
    if base == 1 and n == 1:
        return True
    if base == 0 and n != 1:
        return False
    power = int [math.log[n, base] + 0.5]
    return base ** power == n

print[isPower[127,2]]
print[isPower[128,2]]

print[isPower[27,2]]
print[isPower [27,3]]
print[isPower [28,3]]
print[isPower [2**10,2]]
print[isPower [2**12,2]]

print[isPower[2,2]]
print[isPower[5,5]]
print[isPower[10,1]]

Sample Output:

False                                                                                                         
True                                                                                                          
False                                                                                                         
True                                                                                                          
False                                                                                                         
True                                                                                                          
True                                                                                                          
True                                                                                                          
True                                                                                                          
False 

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 an integer is the power of another integer.
Next: Write a Python program to find a missing number from a list.

In this example, you will learn to compute the power of a number.

To understand this example, you should have the knowledge of the following Python programming topics:

  • Python pow[]
  • Python for Loop
  • Python while Loop

Example 1: Calculate power of a number using a while loop

base = 3
exponent = 4

result = 1

while exponent != 0:
    result *= base
    exponent-=1

print["Answer = " + str[result]]

Output

Answer = 81

In this program, base and exponent are assigned values 3 and 4 respectively.

Using the while loop, we keep on multiplying the result by base until the exponent becomes zero.

In this case, we multiply result by base 4 times in total, so result = 1 * 3 * 3 * 3 * 3 = 81.

Example 2: Calculate power of a number using a for loop

base = 3
exponent = 4

result = 1

for exponent in range[exponent, 0, -1]:
    result *= base

print["Answer = " + str[result]]

Output

Answer = 81

Here, instead of using a while loop, we've used a for loop.

After each iteration, the exponent is decremented by 1, and the result is multiplied by the base exponent number of times.

Both programs above do not work if you have a negative exponent. For that, you need to use the pow[] function in the Python library.

Example 3: Calculate the power of a number using pow[] function

base = 3
exponent = -4

result = pow[base, exponent]

print["Answer = " + str[result]]

Output

Answer = 0.012345679012345678

pow[] accepts two arguments: base and exponent. In the above example, 3 raised to the power -4 is calculated using pow[].

First, assuming you have a specific logarithm operator [many languages provide logarithms to base 10 or base e only], logab can be calculated as logxb / logxa [where x is obviously a base that your language provides].

Python goes one better since it can work out the logarithm for an arbitrary base without that tricky equality above.

So one way or another, you have a way to get logarithm to a specific base. From there, if the log of b in base a is an integer[note 1], then b is a power of a.

So I'd start with the following code, now with added edge-case detection:

# Don't even think about using this for negative powers :-]

def isPower [num, base]:
    if base in {0, 1}:
        return num == base
    power = int [math.log [num, base] + 0.5]
    return base ** power == num

See for example the following complete program which shows this in action:

import math

def isPower [num, base]:
    if base in {0, 1}:
        return num == base
    power = int [math.log [num, base] + 0.5]
    return base ** power == num

print isPower [127,2]       # false
print isPower [128,2]       # true
print isPower [129,2]       # false
print

print isPower [26,3]        # false
print isPower [27,3]        # true
print isPower [28,3]        # false
print isPower [3**10,3]     # true
print isPower [3**129,3]    # true
print

print isPower [5,5]         # true
print isPower [1,1]         # true
print isPower [10,1]        # false

If you're the sort that's worried about floating point operations, you can do it with repeated multiplications but you should test the performance of such a solution since it's likely to be substantially slower in software than it is in hardware. That won't matter greatly for things like isPower[128,2] but it may become a concern for isPower[verybignum,2].

For a non-floating point variant of the above code:

def isPower [num, base]:
    if base in {0, 1}:
        return num == base
    testnum = base
    while testnum < num:
        testnum = testnum * base
    return testnum == num

But make sure it's tested against your largest number and smallest base to ensure you don't get any performance shocks.

[Note 1] Keep in mind here the possibility that floating point imprecision may mean it's not exactly an integer. You may well have to use a "close enough" comparison.

How do you check if a number is power of a number in Python?

pow[number,exponent] function to find the power of the number..
import math. print[math. pow[4,2]] Run. Importing math module in Python..
def power[n,e]: res=0. for i in range[e]: res *= n. return res. print[pow[4,2]] Run. ... .
def power[n, e]: if e == 0: return 1. elif e == 1: return n. else: return [n*power[n, e-1]].

How do you check if a number is a power of another number using recursion in Python?

Python Program to Calculate the Power using Recursion.
Take the base and exponential value from the user..
Pass the numbers as arguments to a recursive function to find the power of the number..
Give the base condition that if the exponential power is equal to 1, return the base number..

How do you check if a number is a power of something?

A simple solution is to repeatedly compute powers of x. If a power becomes equal to y, then y is a power, else not.

How do you check if a number is a power of 10 in Python?

itoa[x, buf, 10]; const size_t bufLen = strlen[buf]; // Check if string contains '1' followed by '0'-s. Another option is to convert the number to floating-point format, use "real" log10 function, and check if the result is an integer.

Chủ Đề