rullzing
rullzing

Reputation: 642

big int giving me wrong results in equality

For some reason I'm getting the wrong result from big int when I test the equality even though the mod result is actually correct! For example, I would like to calculate 2015%2 which results in 1.

When I use big int, I get false when I do this:

fmt.Println((test.Mod(big.NewInt(2015),big.NewInt(2)))==big.NewInt(1))

However, when I use regular int, I get true (which is the correct thing anyway):

fmt.Println(2015%2==1)

Am I supposed to do the equality differently when using big int?

Upvotes: 3

Views: 2647

Answers (2)

peterSO
peterSO

Reputation: 166569

Package big

import "math/big"

func NewInt

func NewInt(x int64) *Int

NewInt allocates and returns a new Int set to x.

func (*Int) Cmp

func (x *Int) Cmp(y *Int) (r int)

Cmp compares x and y and returns:

-1 if x <  y
 0 if x == y
+1 if x >  y

The variables a and b are pointers: *big.Int. Use the Cmp method to compare values. For example,

package main

import (
    "fmt"
    "math/big"
)

func main() {
    a := big.NewInt(42)
    fmt.Printf("a: %[1]T %[1]p %[1]v\n", a)
    b := big.NewInt(42)
    fmt.Printf("b: %[1]T %[1]p %[1]v\n", b)
    fmt.Println("pointers:", a == b)        // compare pointers
    fmt.Println("values:  ", a.Cmp(b) == 0) // compare values

    fmt.Println()
    test := new(big.Int)
    fmt.Println((test.Mod(big.NewInt(2015), big.NewInt(2))).Cmp(big.NewInt(1)) == 0)
}

Playground: https://play.golang.org/p/TH6UzceZ4y

Output:

a: *big.Int 0x1040a0c0 42
b: *big.Int 0x1040a0d0 42
pointers: false
values:   true

true

Upvotes: 6

audionuma
audionuma

Reputation: 343

Have a look at the (*int)Cmp function.

package main

import (
    "fmt"
    "math/big"
)

func main() {
    a := big.NewInt(5)
    b := big.NewInt(5)
    fmt.Println(a == b)
    fmt.Println(a.Cmp(b))
}

Upvotes: 0

Related Questions