You are given two no A And B when A is raised to some power P we get a no X no I want to find the value of X that is closest to B for example if input is 2 and 4 the output should be 4 the thing I tried
def nearestPower(A, B):
x=math.floor(math.log(B,A))
x=x 1
number1=A**x
number2=A**x
if(abs(number1-B)>abs(number2-B)):
return number2
else:
return number1
actually I have no idea how to solve it so I am asking it I just started leaning python
CodePudding user response:
You've got the right idea with math.floor(math.log(B,A))
. But why are you making number1 and number2 the same? The point of x=x 1
is to make number2 the next power of A after number1, e.g.
def nearestPower(A, B):
x=math.floor(math.log(B,A))
number1=A**x
x=x 1
number2=A**x
if(abs(number1-B)>abs(number2-B)):
return number2
else:
return number1