Skip to main content

How to check if a number is divisible by another number in Kotlin

How to check if a number is divisible by another number in Kotlin.

Here's a step-by-step tutorial on how to check if a number is divisible by another number in Kotlin:

Step 1: Get the input numbers

Start by getting the two numbers from the user that you want to check for divisibility.

Step 2: Check for divisibility using the modulo operator

To check if a number is divisible by another number, you can use the modulo operator (%). The modulo operator calculates the remainder when one number is divided by another. If the remainder is 0, it means the first number is divisible by the second number.

Step 3: Write the code

Here are a few code examples to demonstrate how to check if a number is divisible by another number in Kotlin:

Example 1: Using if-else statement

fun main() {
val number = 12
val divisor = 3

if (number % divisor == 0) {
println("Number is divisible by divisor")
} else {
println("Number is not divisible by divisor")
}
}

In this example, we check if the number 12 is divisible by 3. If the remainder of the division is 0, we print "Number is divisible by divisor". Otherwise, we print "Number is not divisible by divisor".

Example 2: Using a function

fun isDivisible(number: Int, divisor: Int): Boolean {
return number % divisor == 0
}

fun main() {
val number = 12
val divisor = 3

if (isDivisible(number, divisor)) {
println("Number is divisible by divisor")
} else {
println("Number is not divisible by divisor")
}
}

In this example, we define a function called isDivisible that takes two parameters (number and divisor) and returns a Boolean indicating whether the number is divisible by the divisor. We then call this function and print the appropriate message based on the result.

Step 4: Run the code

Compile and run the Kotlin code to see the output. If the number is divisible by the divisor, the output will be "Number is divisible by divisor". Otherwise, it will be "Number is not divisible by divisor".

That's it! You now know how to check if a number is divisible by another number in Kotlin.