0

I'm having trouble with desiging a method to express an integer n as an integer pair (base, exponent) such that n == base ^ exponent, for an assignment. Below is the contract for the method. @pre specifies what n has to be, @post defines what the output has to be.

/**
* Writes a number as a power with maximal exponent.
*
* @param n  the number to 'powerize'
* @return  power decomposition of {@code n} with maximal exponent
* @throws IllegalArgumentException  if precondition violated
* @pre {@code 2 <= n}
* @post {@code n == power(\result) &&
*     (\forall int b, int e;
*      2 <= b && 1 <= e && n == b ^ e;
*      e <= \result.exponent)}
*/
public static Power powerize(int n){}

Where the class Power is just a Pair instance.

I already managed to solve this problem using a naive approach, in which I compute the value of the base and exponent by computing log(n) / log(b) with 2 <= b <= sqrt(n). But the assignment description says I have to produce an ellegant & efficient method and I couldn't find a way to compute this more efficiently.

Ph03n1x
  • 3
  • 2
  • you can define a class with two properties `base` and `exponent` and implement getter and setter for them to be accessed using objects of the same class – Naman Feb 23 '16 at 23:16
  • Iterate `e` in `log(n) / log(2) >= e >= 1` and calculate `b = exp(log(n) / e)`. –  Feb 24 '16 at 00:02

1 Answers1

0

After consulting some books I designed the following solution:

Input int n:
Let p1...pm be m unique primes.
Then we can express n as:

    n = p1e1 x ... x pmem.

Then compute the gcd d of e1 ... em using the euclidean algorithm.
Then we express n as:

    n = (p1e1/d x ... x pmem/d)d.

now we have:

    b = p1e1/d x ... x pmem/d
    e = d
return new Power(b, e)
Ph03n1x
  • 3
  • 2