Home > Software engineering >  Golang BigInt division
Golang BigInt division

Time:07-29

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?

CodePudding user response:

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.

  • Related