如何在Go中使用大整数? [英] How to work with large integers in Go?

查看:102
本文介绍了如何在Go中使用大整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对Go中的int64的较大值执行求幂和除法等操作,但是我遇到了溢出问题.我尝试将它们转换为float64,但随后遇到其他问题.这是我尝试过的.

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.

我有一个整数变量,必须将其转换为float64才能使用方便的数学程序包( https://golang.org/pkg/math ).

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

但是,当整数变量太大时,它不能正确转换.我假设这是因为大小大于float64.例如:

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

我正在尝试使用math.Mod,math.Pow10和math.Log10.上面显示了大量的数字,我将如何执行以下逻辑?

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

推荐答案

这个问题对我来说不是很清楚,但是我假设您想对大整数执行操作,并且仅尝试使用float64.

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.

在这种情况下,正确的工具是 math/big包.这是使用它来提取int64的第n个十进制数字的方法:

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()
}

这篇关于如何在Go中使用大整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆