How to check if integer multiplication will overflow in Kotlin

2 Answers

0 votes
object OverflowCheck {
    fun multiplyWillOverflow(x: Int, y: Int): Boolean {
        if (x == 0) return false
        if (y > Int.MAX_VALUE / x) return true
        if (y < Int.MIN_VALUE / x) return true
        return false
    }

    @JvmStatic
    fun main(args: Array<String>) {
        var x: Int = 34
        var y: Int = 14727836
        println(if (multiplyWillOverflow(x, y)) "true" else "false")

        x = 133883
        y = 18999383
        println(if (multiplyWillOverflow(x, y)) "true" else "false")
    }
}


 
/*
run:
 
false
true
 
*/

 



answered May 18, 2025 by avibootz
0 votes
fun multiplyWillOverflow(x: Int, y: Int): Boolean {
	if (x == 0) return false
    if (y > Int.MAX_VALUE / x) return true
    if (y < Int.MIN_VALUE / x) return true
    return false
}

fun main() {
 	var x: Int = 34
	var y: Int = 14727836
    println(if (multiplyWillOverflow(x, y)) "true" else "false")

    x = 133883
    y = 18999383
    println(if (multiplyWillOverflow(x, y)) "true" else "false")
}


 
/*
run:
 
false
true
 
*/

 



answered May 18, 2025 by avibootz
...