First determine any natural number k
for which n ^ k >= m
. Then refine your estimate to find the smallest such k
.
It's easiest to find the initial estimate for k
as a power of 2. Have a temporary value which holds n ^ k
. Start from k = 1
, repeatedly multiply k
by 2, and square your temporary variable, until your k
is sufficiently big.
Your real k
will be greater than half the estimate you found. Numbers in that range have log2(k)
bits. Check each bit, starting from the most significant one. For each such bit, calculate n ^ k
for two values of k
: with that bit equal to 0 and 1. Compare with m
- this will tell you the value of that bit. Proceed to lower-significant bits, until you get to bit 0 (least significant bit).
I am not sure you are allowed to assume that calculating n ^ k
has O(1) complexity. If not, you have to store intermediate results for all n ^ k
calculations at first stage, or alternatively, use sqrt
to calculate lesser powers of n
.