英文:
Golang BigInt division
问题
我有一个关于函数的问题,我不明白为什么会发生这种情况。问题是:我有一个很大的数字,但是当我尝试进行一些除法运算时,结果都是零。
代码如下:
for {
fmt.Println("number is", number)
key := number.Mod(number, big.NewInt(10))
fmt.Println("key", key)
first := new(big.Int).Div(number, big.NewInt(10))
fmt.Println("first", first)
number = first
fmt.Println(number)
// number = 0 always as a fisrt variable too
...
}
退出的示例:
number is 6689502913449127057588118054090372586752746333138029810295671352301633557244962989366874165271984981308157637893214090552534408589408121859898481114389650005964960521256960000000000000000000000000000
key 0
first 0
0
数字获取正确,Mod 操作似乎也正确。但是 Div 操作不正确。问题出在哪里?如何计算大数的基本除法运算?
英文:
I have a problem with function and i don't understand why it happen. The problem is: i have a big number, but when i'm trying to make some operations of division - I have zeros.
The code is:
for {
fmt.Println("number is", number)
// key := number % 10
key := number.Mod(number, big.NewInt(10))
fmt.Println("key", key)
// number = number / 10
first := new(big.Int).Div(number, big.NewInt(10))
fmt.Println("first ", first)
number = first
fmt.Println(number) //number = 0 always as a fisrt variable too
... }
The example of exit is:
number is 6689502913449127057588118054090372586752746333138029810295671352301633557244962989366874165271984981308157637893214090552534408589408121859898481114389650005964960521256960000000000000000000000000000
key 0
first 0
0
Number is getting on correnctly, Mod operation is seems correctly too. Div operation is not. What the point is? How can i calculate basic divisions of big numbers?
答案1
得分: 2
问题出在这一行代码上:
key := number.Mod(number, big.NewInt(10))
你调用了number.Mod()
,它是Int.Mod()
,它会修改接收者number
,将其设置为模数0
,所以在这之后number
将变为零。
你需要使用一个新的big.Int
,就像你在Div()
操作中使用的那样:
key := new(big.Int).Mod(number, big.NewInt(10))
在Go Playground上试一试。
还要注意,有一个Int.DivMod()
可以同时执行这两个操作(Div()
和Mod()
)。
此外,为了加快循环速度,你应该创建并重复使用*big.Int
值,而不是在每次迭代中创建并丢弃它们。最简单的方法是创建并重复使用10
:
var ten = big.NewInt(10)
还要创建并重复使用模数和除法结果的值。
英文:
The problem is this line:
key := number.Mod(number, big.NewInt(10))
You call number.Mod()
which is Int.Mod()
which modifies the receiver which is number
, it sets it to the modulus which is 0
, so after this number
will be zeroed.
You have to use a new big.Int
, just as you used for the Div()
operation:
key := new(big.Int).Mod(number, big.NewInt(10))
Try it on the Go Playground.
Also note that there is Int.DivMod()
which performs both these 2 operations (Div()
and Mod()
).
Also note that to speed up your loop, you should create and reuse *big.Int
values, and not create and throw them away in each iteration. The most trivial is to create and reuse 10
:
var ten = big.NewInt(10)
Also create and reuse values for the mod and div results.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论