-1

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 Answers1

7

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.

JimB
  • 104,193
  • 13
  • 262
  • 255