How to work with large integers in Go?

huangapple go评论81阅读模式
英文:

How to work with large integers in Go?

问题

我需要在Go语言中对int64类型的大数进行指数运算和除法等操作,但是我遇到了溢出的问题。我尝试将它们转换为float64类型,但是又遇到了其他问题。以下是我尝试过的方法。

我有一个整数变量,我需要将其转换为float64类型才能使用方便的math包(https://golang.org/pkg/math)。

然而,当整数变量太大时,它无法正确转换。我猜测这是因为整数的大小超过了float64的范围。例如:

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

我想使用math.Mod、math.Pow10和math.Log10函数。如何使用上述显示的大数进行以下逻辑操作?

int(math.Mod(float64(123) / math.Pow10(1), 10))) // 获取第二位数字
英文:

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

答案1

得分: 5

问题对我来说不太清楚,但我猜你想对大整数进行操作,之前只是尝试使用了float64。

在这种情况下,正确的工具是math/big包。以下是如何使用它来提取int64的第n个小数位:

// 第一个数字是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()
}

math/big包的文档

英文:

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

答案2

得分: 1

你可以尝试将整数转换为字符串,然后提取转换后字符串中的数字。

// n >= 1
func NthDigit(num int, n int) int {
    return int(strconv.Itoa(num)[n-1]) - int('0')
}

请注意,这是一个用于提取整数中第n位数字的Go函数。

英文:

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

huangapple
  • 本文由 发表于 2017年4月8日 14:29:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/43290945.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定