1

I need to perform operations, such as exponentiation and division, on large values of int64 in Go, but I have problems with overflow. I tried converting them to float64, but then I run into other problems. Here is what I tried.

I have an integer variable, which I had to cast into a float64 to use the handy math package (https://golang.org/pkg/math).

However, it doesn't cast correctly when the integer variable is too big. I'm assuming it's because the size is bigger than float64. ex:

fmt.Printf("%f",float64(111111111111111110)) //Outputs 111111111111111104.000000

I'm trying to use math.Mod, math.Pow10, and math.Log10. How would I be able to do the following logic, but with a large number shown above?

int(math.Mod(float64(123) / math.Pow10(1),10))) // Gets the second digit
Zoyd
  • 3,449
  • 1
  • 18
  • 27
WCGPR0
  • 751
  • 1
  • 11
  • 24
  • Possible duplicate of [Why Are Floating Point Numbers Inaccurate?](http://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate) – Paul Hankin Apr 08 '17 at 14:05
  • 1
    It turns out that the OP did not intend to ask about floating points at all, after all, so it is not a duplicate of that question. – Zoyd Apr 09 '17 at 08:29

2 Answers2

5

The question is not really clear to me, but I assume you want to perform operations on large integers and were only using float64 as a try.

In that case, the right tool is the math/big package. Here is how to use it to extract the nth decimal digit of an int64:

// first digit is n=0
func nthDigit(i int64, n int64) int64 {
    var quotient big.Int
    quotient.Exp(big.NewInt(10), big.NewInt(n), nil)

    bigI := big.NewInt(i)
    bigI.Div(bigI, &quotient)

    var result big.Int
    result.Mod(bigI, big.NewInt(10))

    return result.Int64()
}
Zoyd
  • 3,449
  • 1
  • 18
  • 27
  • Sorry for the bad phrasing of the question, but thanks for pointing me in the right package to use! I noticed this package doesn't have a log function, is this also I can do with big ints (for example to get the amount of digits in i)? – WCGPR0 Apr 08 '17 at 21:12
  • 1
    There is no Log indeed, but there is BitLen, and lb(n) = BitLen(n)-1 (lb = binary logarithm). From there, Log(n) = lb(n)/lb(10). – Zoyd Apr 09 '17 at 08:18
  • 1
    I edited the question so that it reflects what you intended to ask. This will make it easier to search for this question later. Of course you can still edit it if you feel that my edit was not what you meant to say. – Zoyd Apr 09 '17 at 08:29
1

You can try to convert the int to string, and then fetch the digits in the converted string,

// n >= 1
func NthDigit(num int, n int) int {
    return int(strconv.Itoa(num)[n-1]) - int('0')
}
Qiang Jin
  • 4,427
  • 19
  • 16