python 冪運算 整數
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.
為了簡單地解決這個問題,我們將使用math模塊中的log()函數 。 數學模塊為我們提供了各種數學運算,在這里我們將使用該模塊中的log()函數 。 在Python中, log()函數的工作方式與數學中的日志工作相同。 在這里,用戶將為我們提供兩個正值a和b ,我們必須檢查一個數字是否是Python中另一個數字的冪 。 這個想法是簡單找到一個基極b的對數,并采取的它并給它分配的整數部分為變量s。 之后,只需檢查s的b的冪是否等于a,則a是另一個數字b的冪 。 在解決此問題之前,我們將看到解決該問題的算法并嘗試理解它。
Algorithm to solve this problem:
解決此問題的算法:
Initially, we will import the math module in the program.
最初,我們將把數學模塊導入程序中。
Takes the positive value of a and b from the user.
從用戶處獲得a和b的正值。
Find the log of a base b and assign its integer part to variable s.
找到一個基極b的對數,并分配其整數部分到變量s。
Also, find the b to the power s and assign it to another variable p.
同樣,找到b的冪s并將其分配給另一個變量p 。
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.
檢查p是否等于a,那么a是另一個數字b的冪,而print a是另一個數字b的冪。
Now, we will write the Python program by the implementation of the above algorithm.
現在,我們將通過上述算法的實現編寫Python程序。
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.
翻譯自: https://www.includehelp.com/python/check-whether-a-number-is-a-power-of-another-number-or-not.aspx
python 冪運算 整數