Skip to content

Commit

Permalink
Add SafeDivBig
Browse files Browse the repository at this point in the history
  • Loading branch information
fmoletta committed Sep 26, 2023
1 parent a72704d commit 8dbdbcb
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
13 changes: 13 additions & 0 deletions pkg/utils/math_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package utils

import (
"math"
"math/big"

"github.com/pkg/errors"
)
Expand Down Expand Up @@ -50,3 +51,15 @@ func DivCeil(x uint, y uint) uint {
}
return q
}

// Performs integer division between x and y; fails if x is not divisible by y.
func SafeDivBig(x *big.Int, y *big.Int) (*big.Int, error) {
if y.Cmp(big.NewInt(0)) == 0 {
return &big.Int{}, errors.New("SafeDiv: Attempted to divide by zero")
}
q, r := x.DivMod(x, y, new(big.Int))
if r.Cmp(big.NewInt(0)) != 0 {
return &big.Int{}, errors.Errorf("SafeDiv: %s is not divisible by %s", x.Text(10), y.Text(10))
}
return q, nil
}
46 changes: 46 additions & 0 deletions pkg/utils/math_utils_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package utils_test

import (
"math/big"
"testing"

. "github.com/lambdaclass/cairo-vm.go/pkg/utils"
)

func TestSafeDivBigOkSmallNumbers(t *testing.T) {
a := big.NewInt(10)
b := big.NewInt(5)
expected := big.NewInt(2)
val, err := SafeDivBig(a, b)
if err != nil || val.Cmp(expected) != 0 {
t.Error("Wrong value returned by SafeDivBig")
}
}

func TestSafeDivBigOkBigNumbers(t *testing.T) {
a, _ := new(big.Int).SetString("1354671610274991796869769298862800192014", 10)
b, _ := new(big.Int).SetString("37853847583", 10)
expected, _ := new(big.Int).SetString("35786893453952854863476753458", 10)
val, err := SafeDivBig(a, b)
if err != nil || val.Cmp(expected) != 0 {
t.Error("Wrong value returned by SafeDivBig")
}
}

func TestSafeDivBigErrNotDivisible(t *testing.T) {
a := big.NewInt(10)
b := big.NewInt(7)
_, err := SafeDivBig(a, b)
if err == nil {
t.Error("SafeDivBig should have failed")
}
}

func TestSafeDivBigErrZeroDivison(t *testing.T) {
a := big.NewInt(10)
b := big.NewInt(0)
_, err := SafeDivBig(a, b)
if err == nil {
t.Error("SafeDivBig should have failed")
}
}

0 comments on commit 8dbdbcb

Please sign in to comment.