Check whether a number is a power of another number or not in Python

Here, we will learn how to check if a number is a power of another number or not in Python programming language? By Bipin Kumar Last updated : January 05, 2024

Problem statement

Here, the user will provide us two positive values a and b and we have to check whether a number is a power of another number or not in Python.

Checking whether a number is a power of another number

To solve this problem simply, we will use the log() function from the math module. The math module provides us various mathematical operations. In Python working of log() function, is the same as log work in mathematics. The idea is simple to find the log of a base b and takes the integer part of it and assigns it to a variable s. After this just check if s to the power of b is equal to a then a is the power of another number b. Before going to solve this, we will see the algorithm to solve this problem and try to understand it.

Algorithm

Algorithm to solve this problem:

  1. Initially, we will import the math module in the program.
  2. Takes the positive value of a and b from the user.
  3. Find the log of a base b and assign its integer part to variable s.
  4. Also, find the b to the power s and assign it to another variable p.
  5. Check if p is equal to a then a is a power of another number b and print a is the power of another number b.

Now, we will write the Python program by the implementation of the above algorithm.

Python code to check whether a number is a power of another number or not

# importing the module
import math

# input the numbers
a, b = map(int, input("Enter two values: ").split())

s = math.log(a, b)

p = round(s)

if (b**p) == a:
    print("{} is the power of another number {}.".format(a, b))
else:
    print("{} is not the power of another number {}.".format(a, b))

Output

The output of the above example is:

RUN 1:
Enter two values: 1228 2
1228 is the power of another number 2.
	
RUN 2:
Enter two values: 15625 50
15625 is not the power of another number 50.

To understand the above program, you should have the basic knowledge of the following Python topics:

Python Basic Programs »


Related Programs

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.