Golang - module using a math package

View documentation - http://golang.org/pkg/math/big/

Mod sets z to the module x% y for y! = 0 and returns z. If y == 0, panic occurs with division by zero. Mod implements the Euclidean module (as opposed to Go); see the DivMod section for more details.

10% 4 = 2, but I get 8 with this (using math / big package to do the same) - 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 had something wrong. Where is the mistake?

+4
source share
2 answers

This is because it SetBytesdoes not do what you think! Use instead SetInt64.

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

, , int64 , SetString:

n := new(big.Int)
n.SetString("456135478645413786350", 10)
+4

julienc , SetBytes, , this:

func int2bytes(num int) (b []byte) {
    b = make([]byte, 4)
    binary.BigEndian.PutUint32(b, uint32(num))
    return
}
func main() {
    ten := new(big.Int)
    ten.SetBytes(int2bytes(10))

    four := new(big.Int)
    four.SetBytes(int2bytes(4))

    fmt.Println(ten, four)

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

    fmt.Println("mod", tenmodfour)
}
+2

Source: https://habr.com/ru/post/1543685/


All Articles