Search code examples
ralgorithmbigintegerbigintsquare-root

How to find the square root of a big integer in R language? (package gmp doesn't have sqrt for bigz)


I'm trying to find the square root of a big integer in R language. I'm using package gmp which provides bigz for big integers but it seems it's missing a function for square root. I'm opened to using another package for big integers if needed.

library(gmp)
 sqrt(as.bigz("113423713055421844361000443349850346743"))
Error: 'Math.bigz' is not implemented yet

Alternatively I'm looking for a way to implement sqrt using bigz.


Solution

  • This type of problem is exactly what the Rmpfr package was built for.

    library(Rmpfr)
    a <- mpfr("113423713055421844361000443349850346743", 128)  ## specify the number of bits
    sqrt(a)
    1 'mpfr' number of precision  128   bits 
    [1] 10650056950806500000.00000005163589039117
    

    It should be noted that in order to access the power of this package, you must first declare your variable as an mpfr object. Once you have done this, you can easily perform any number of arithmetic operations to any number of precision of bits (up to memory).