TITLE: How to quickly determine whether a given natural number is a power of another natural number?
QUESTION [16 upvotes]: We have a natural number $n>1$. We want to determine whether there exist
natural numbers $a, k>1$ such that $n = a^k$. 
Please suggest a polynomial-time algorithm.

REPLY [4 votes]: The computer algebra system GAP performs this test and determines a
smallest root $a$ of a given integer $n$ quite efficiently.
The following is copied directly from its source code (file gap4r6/lib/integer.gi),
and should be self-explaining:
#############################################################################
##
#F  SmallestRootInt( <n> )  . . . . . . . . . . . smallest root of an integer
##
InstallGlobalFunction(SmallestRootInt,

  function ( n )

    local   k, r, s, p, l, q;

    # check the argument
    if   n > 0  then k := 2;  s :=  1;
    elif n < 0  then k := 3;  s := -1;  n := -n;
    else return 0;
    fi;

    # exclude small divisors, and thereby large exponents
    if n mod 2 = 0  then
        p := 2;
    else
        p := 3;  while p < 100  and n mod p <> 0  do p := p+2;  od;
    fi;
    l := LogInt( n, p );

    # loop over the possible prime divisors of exponents
    # use Euler's criterion to cast out impossible ones
    while k <= l  do
        q := 2*k+1;  while not IsPrimeInt(q)  do q := q+2*k;  od;
        if PowerModInt( n, (q-1)/k, q ) <= 1  then
            r := RootInt( n, k );
            if r ^ k = n  then
                n := r;
                l := QuoInt( l, k );
            else
                k := NextPrimeInt( k );
            fi;
        else
            k := NextPrimeInt( k );
        fi;
    od;

    return s * n;
end);