What is the best (most efficient) algorithm for finding all integer power roots of a number?
That is, given a number n
, I want to find b
(base) and e
(exponent) such that
n = be
I want to obtain all the possible value pairs of b
and e
Ps: n
b
and e
are to be positive integers .
I think brute force approach should work: try all
e
s from 2 (1 is a trivial solution) and up, takingr = n ^ 1/e
, adouble
. Ifr
is less than 2, stop. Otherwise, computeceil(r)^e
andfloor(r)^e
, and compare them ton
(you needceil
andfloor
to compensate for errors in floating point representations). Assuming your integers fit in 64 bits, you would not need to try more than 64 values ofe
.Here is an example in C++:
When invoked with 65536, it produces this output:
It depends on the dimensions of the task whether my approach will suite your needs.
First of all there is one obvious solution: e = 1, right? From then on if you want to find all the solutions: all the algorithms I can think of require to find some prime factor of n. If this is just a single independent task nothing better than brute force on the primes can be done (if I am not wrong). After you find the first prime factor p and its corresponding exponent (i.e the highest number k such that p^k / n) you need to check for e only the divisors of k. For every such exponent l (again l iterates all divisors of k) you can use binary search to see if the lth root of n is integer (equivalent to finding new solution).
Mix the approaches of interjay and dasblinkenlight. First find all small prime factors (if any) and their exponents in the prime factorisation of
n
. The appropriate value of 'small' depends onn
, for medium sizedn
,p <= 100
can be sufficient, for largen
,p <= 10000
orp <= 10^6
may be more appropriate. If you find any small prime factors, you know thate
must divide the greatest common divisor of all exponents you found. Quite often, thatgcd
will be 1. Anyway, the range of possible exponents will be reduced, ifn
has no small prime factors, you know thate <= log(n)/log(small_limit)
, which is a good reduction fromlog(n)/log(2)
, if you have found a couple of small prime factors, thegcd
of their exponents isg
, and the remaining cofactor ofn
ism
, you only need to check the divisors ofg
not exceedinglog(m)/log(small_limit)
.First find the prime factorization of
n
:n = p1e1 p2e2 p3e3 ...
Then find the greatest common divisor
g
ofe1
,e2
,e3
, ... by using the Euclidean algorithm.Now for any factor
e
ofg
, you can use:b = p1e1/e p2e2/e p3e3/e ...
And you have
n = be
.