Skip to content
DeveloperMemos

Checking if a Number is a Multiple of 5 in Kotlin

Kotlin, Modulo Operator, Mathematical Operations1 min read

The easiest way to check if a number is a multiple of 5 in Kotlin is to use the modulo operator (%). The modulo operator returns the remainder of a division operation. In other words, it returns the amount left over after dividing one number by another. If the result of the modulo operation is 0, it means that the number is a multiple of 5.

Here is an example of how to check if a number is a multiple of 5 using the modulo operator:

1fun main(args: Array<String>) {
2 val num = 20
3 if (num % 5 == 0) {
4 println("$num is a multiple of 5")
5 } else {
6 println("$num is not a multiple of 5")
7 }
8}

In this example, the variable num is assigned the value 20. The if statement then performs the modulo operation num % 5 and checks if the result is equal to 0. If the result is 0, the program prints "20 is a multiple of 5". If the result is not 0, the program prints "20 is not a multiple of 5".

You can also write this code using a when expression, which is a concise way of writing multiple if-else statements in Kotlin. Here is an example:

1fun main(args: Array<String>) {
2 val num = 25
3 val result = when (num % 5) {
4 0 -> "$num is a multiple of 5"
5 else -> "$num is not a multiple of 5"
6 }
7 println(result)
8}

In this example, the when expression performs the modulo operation num % 5 and matches the result with a corresponding string. If the result is 0, the program prints "25 is a multiple of 5". If the result is not 0, the program prints "25 is not a multiple of 5".

In conclusion, checking if a number is a multiple of 5 in Kotlin is a simple task that can be done using the modulo operator. Whether you use an if statement or a when expression, the logic remains the same. With these techniques, you can easily add this functionality to your Kotlin projects and perform other mathematical operations with ease.