Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang - modulus using math big package

Tags:

go

Reading up the documentation - http://golang.org/pkg/math/big/

Mod sets z to the modulus x%y for y != 0 and returns z. If y == 0, a division-by-zero run-time panic occurs. Mod implements Euclidean modulus (unlike Go); see DivMod for more details.

10%4 = 2 but I get 8 with this (using the math/big package to do the same thing) - http://play.golang.org/p/_86etDvLYq

package main

import "fmt"
import "math/big"
import "strconv"

func main() {
    ten := new(big.Int)
    ten.SetBytes([]byte(strconv.Itoa(10)))

    four := new(big.Int)
    four.SetBytes([]byte(strconv.Itoa(4)))

    tenmodfour := new(big.Int)
    tenmodfour = tenmodfour.Mod(ten, four)

    fmt.Println("mod", tenmodfour)

}

I most likely got something wrong. Where's the mistake?

like image 262
sat Avatar asked Dec 26 '22 08:12

sat


1 Answers

It's because SetBytes is not doing what you think! Use SetInt64 instead.

ten := new(big.Int)
ten.SetBytes([]byte(strconv.Itoa(10)))

four := new(big.Int)
four.SetBytes([]byte(strconv.Itoa(4)))

fmt.Println(ten, four)

Result:

12592 52

And indeed, 12592%52 == 8

If you want to use numbers bigger than what int64 lets you manipulate, you can also use the SetString function:

n := new(big.Int)
n.SetString("456135478645413786350", 10)
like image 50
julienc Avatar answered Jan 12 '23 14:01

julienc