2

Overflows don't seem to be part of the builtin packages in go.

What is the best way to test that you don't overflow when multiplying 2 integers ?

Something similar to Java Math.multiplyExact ...

1 Answer 1

2

It'd be possible for you to write your own multiplyExact based on the suggestions on this thread:

https://groups.google.com/forum/#!msg/golang-nuts/h5oSN5t3Au4/KaNQREhZh0QJ

const mostNegative = -(mostPositive + 1)
const mostPositive = 1<<63 - 1

func multiplyExact(a, b int64) (int64, error) {
    result := a * b
    if a == 0 || b == 0 || a == 1 || b == 1 {
        return result, nil
    }
    if a == mostNegative || b == mostNegative {
        return result, fmt.Errorf("Overflow multiplying %v and %v", a, b)
    }
    if result/b != a {
        return result, fmt.Errorf("Overflow multiplying %v and %v", a, b)
    }
    return result, nil
}

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.