英文:
Golang: odd big Int behavior
问题
所以我刚开始学习Go语言,对编程一般也不太熟悉,所以希望不会因为问一些愚蠢的问题而再次被投票降低分数。
我正在解决项目欧拉问题,并在第25题“1000位斐波那契数”遇到了一些奇怪的行为。以下是我编写的代码,导致了这种行为。
package main
import (
"fmt"
"math/big"
)
func main() {
index := 2
l := new(big.Int)
pl := big.NewInt(1)
i := big.NewInt(1)
for {
l = i
i.Add(i, pl)
pl = l
index++
if len(i.String()) == 1000 {
break
}
}
fmt.Println(i, "\nindex: ", index)
}
显然,这并没有生成正确的答案,所以在确定原因时,我无意中发现了一种生成2的幂的巧妙方法。我进行了以下更改,这样确实生成了正确的结果。
package main
import (
"fmt"
"math/big"
)
func main() {
index := 2
l := new(big.Int)
pl := big.NewInt(1)
i := big.NewInt(1)
for {
l.Set(i)
i.Add(i, pl)
pl.Set(l)
index++
if len(i.String()) == 1000 {
break
}
}
fmt.Println(i, "\nindex: ", index)
}
我的问题是,第一个示例中发生了什么,导致每个big Int变量都被设置为i的值,为什么如果这不是正确的big Int变量赋值方式,它没有生成错误?i = l等是否是合法的big Int操作,只是在这种情况下不正确?
英文:
So I am new to Go and fairly inexperienced with programming in general so I hope I don't get downvoted again for asking stupid questions.
I am working my way through the project euler problems and at problem 25 "1000-digit Fibonacci number" I encountered what seems to be strange behavior. The following is the code I wrote that resulted in this behavior.
package main
import (
"fmt"
"math/big"
)
func main() {
index := 2
l := new(big.Int)
pl := big.NewInt(1)
i := big.NewInt(1)
for {
l = i
i.Add(i, pl)
pl = l
index++
if len(i.String()) == 1000 {
break
}
}
fmt.Println(i, "\nindex: ", index)
}
Naturally this did not generate the correct answer so in the process of determining why I discovered that I had inadvertently discovered a neat way to generate powers of 2. I made the following changes and this did generate the correct result.
package main
import (
"fmt"
"math/big"
)
func main() {
index := 2
l := new(big.Int)
pl := big.NewInt(1)
i := big.NewInt(1)
for {
l.Set(i)
i.Add(i, pl)
pl.Set(l)
index++
if len(i.String()) == 1000 {
break
}
}
fmt.Println(i, "\nindex: ", index)
}
My question is what is happening in the first example that causes each big Int variable to be set to the value of i and why this did not generate an error if this was not the correct way to assign a big Int var value? Is i = l, etc a legitimate big Int operation that is simply incorrect for this situation?
答案1
得分: 7
这里的代码:
l = i
和
pl = l
并不像你想的那样工作。
l
、pl
和 i
都是指针,将它们互相赋值只会复制指针的值,而不是 big.Int
的值。
执行 l = i
后,l
现在与 i
具有相同的指针值,指向相同的 big.Int
。当你使用 l.Set(i)
时,它会将 l
的 big.Int
值设置为 i
的 big.Int
值,但 l
和 i
仍然指向两个不同的值。
英文:
The lines
l = i
and
pl = l
aren't doing what you think they are.
l
, pl
, and i
are pointers, and assigning them to each other copies the pointer value, not the big.Int
value.
After executing l = i
, l
is now the same pointer value as i
, pointing to the same big.Int
. When you use l.Set(i)
, it sets l
's big.Int
value to i
's big.Int
value, but l
and i
still point to two separate values.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论