How to check if integer multiplication will overflow in Go

1 Answer

0 votes
package main
 
import (
    "fmt"
)
 
// math.MaxInt64 = 9223372036854775807
 
func multiplyWillOverflow(x, y uint64) bool {
   if x <= 1 || y <= 1 {
     return false
   }
   
   d := x * y
   
   return d / y != x
}
 
func main() {
    x, y := uint64(3), uint64(1472783642)
    fmt.Println(multiplyWillOverflow(x, y))
     
    x, y = uint64(9223372036854775807), uint64(5848)
    fmt.Println(multiplyWillOverflow(x, y))
}
 
 
  
/*
run:
 
false
true
  
*/

 



answered May 18, 2025 by avibootz
...