Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nth root of BigInteger

I'm using a BigInteger object. With normal ints or longs, I can use Math.pow(number, 1/nth root) to get the nth root. However, this will not work with a BigInteger. Is there a way I can do this?

I do not actually need the root, just to know if it is a perfect power. I'm using this to figure out if the given BigInteger is a perfect square/cube/etc.

like image 634
James McDowell Avatar asked Jun 15 '15 20:06

James McDowell


People also ask

How do you find the fifth root in Java?

Lets say I do something like double z = Math. pow(5, 5) . I do a System. out on this once it gets the value and it will print a result of 3125 .

How many bits can BigInteger hold?

The BigInteger class stores a number as an array of unsigned, 32-bit integer "digits" with a radix, or base, of 4294967296.

How do I find roots in Java?

Java sqrt() method with ExamplesMath. sqrt() returns the square root of a value of type double passed to it as argument. If the argument is NaN or negative, then the result is NaN. If the argument is positive infinity, then the result is positive infinity.


1 Answers

Newton's method works perfectly well with integers; here we compute the largest number s for which sk does not exceed n, assuming both k and n are positive:

function iroot(k, n)
    k1 := k - 1
    s := n + 1
    u := n
    while u < s
        s := u
        u := ((u * k1) + n // (u ** k1)) // k
    return s

For instance, iroot(4, 624) returns 4 and iroot(4, 625) returns 5. Then you can perform the exponentiation and check the result:

function perfectPower(k, n)
    return (k ** iroot(k, n)) == n

For instance, perfectPower(2, 625) and perfectPower(4, 625) are both true, but perfectPower(3, 625) is false.

I'll leave it to you to translate to Java BigInteger.

like image 192
user448810 Avatar answered Sep 22 '22 10:09

user448810