3
$\begingroup$

I wanted to know how would I use Mathematica in order to check if the number is a perfect power I saw the algorithm but couldn't grasp it enough to implement it, so can anybody help?

$\endgroup$
  • 3
    $\begingroup$ Well, you could just use FactorInteger, for example. $\endgroup$ – Leonid Shifrin Feb 13 '14 at 22:05
4
$\begingroup$

The function below returns the power of n.

power[n_] := GCD @@ (FactorInteger[n][[All, 2]])

example:

power[3111696]

returns 4 because3111696=2^4*3^4*7^4

If you deal with very large numbers where FactorInteger simply can't help, you could use trial exponents IntegerQ[n^(1/m)] for m=2,3,4,.... Where to stop (I mean m) depends on the length of the number.

$\endgroup$
0
$\begingroup$

Inspired by tchronis's answer and Leonid's comment I came up with

powers[int_] := FactorInteger[int][[All, 2]]
perfectPowerQ[int_] := (GCD @@ powers[int] > 1)

powers tells you what powers the prime factors are raised to to get the required number while perfectPowerQ checks that all these powers are the same.

$\endgroup$
  • 2
    $\begingroup$ I think you have to use GCD as in @tchronis's answer (GCD@@[powers[int]]>1). Those factors do not have to be the same. For example, perfectPowerQ[144] gives False using your code. $\endgroup$ – Yi Wang Feb 14 '14 at 7:56
  • $\begingroup$ Oh, you are right. Sneaky. Edited that correction in. $\endgroup$ – evanb Feb 14 '14 at 19:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.