I need to find all monomials in the form AX that when evaluated falls within a range from m to n. It is safe to say that the base A is greater than 1, the power X is greater than 2, and only integers need to be used. For example, in the range 50 to 100, the solutions would be:
2^6
3^4
4^3
My first attempt to solve this was to brute force all combinations of A and X that make “sense.” However this becomes too slow when used for very large numbers in a big range since these solutions are used in part of much more intensive processing. Here is the code:
def monoSearch(min, max):
base = 2
power = 3
while 1:
while base**power < max:
if base**power > min:
print "Found " + repr(base) + "^" + repr(power) + " = " + repr(base**power)
power = power + 1
base = base + 1
power = 3
if base**power > max:
break
I could remove one base**power by saving the value in a temporary variable but I don’t think that would make a drastic effect. I also wondered if using logarithms would be better or if there was a closed form expression for this. I am open to any optimizations or alternatives to finding the solutions.
Don’t search; consider the endpoints.
For example, all the solutions with
x == 3are such thatais between the cube root ofmand the cube root ofn. So calculate those cube roots and use the range of integers in between. Sinceais at least 2, the maximumxis log base 2 ofn, so that’s how you know when to stop.This may miss a couple of values due to floating-point imprecision, unfortunately.