Home » Python » Python programs

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?
Submitted by Bipin Kumar, on November 21, 2019

To solve this problem simply, we will use the log() function from the math module. The math module provides us various mathematical operations and here we will use the log() function from this module. In Python working of log() function, is the same as log work in mathematics. 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. 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 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.

Program:

# 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

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.