How to check if a number is divisible by all the numbers in a given list in Kotlin
How to check if a number is divisible by all the numbers in a given list in Kotlin.
Here's a step-by-step tutorial on how to check if a number is divisible by all the numbers in a given list using Kotlin.
Step 1: Define the number and the list of divisors
- Start by declaring a variable to store the number you want to check for divisibility. For example, let's say the number is
num. - Next, create a list of divisors that you want to check the number against. For example, let's say the list is
divisors.
Step 2: Implement the divisibility check
- Use the
allfunction in Kotlin to check if the number is divisible by all the divisors in the list. Theallfunction returns true if all the elements in the list satisfy the given condition. - Inside the
allfunction, use the modulo operator%to check ifnumis divisible by each divisor. If the remainder is zero, it meansnumis divisible by that divisor. Otherwise, it meansnumis not divisible by that divisor. - If any of the divisors return false for the divisibility check, the
allfunction will return false. Otherwise, it will return true.
Here's an example implementation:
fun isDivisible(num: Int, divisors: List<Int>): Boolean {
return divisors.all { num % it == 0 }
}
Step 3: Test the implementation
- Create a sample number and a list of divisors to test the implementation.
- Call the
isDivisiblefunction with the number and the list of divisors as arguments. - Print the result to check if the number is divisible by all the divisors.
Here's an example test:
fun main() {
val num = 15
val divisors = listOf(3, 5)
val result = isDivisible(num, divisors)
println("Is $num divisible by all the divisors? $result")
}
Output:
Is 15 divisible by all the divisors? true
In this example, num is divisible by both 3 and 5, so the function returns true.
You can try running the code with different numbers and divisors to test different scenarios.
That's it! You now have a step-by-step tutorial on how to check if a number is divisible by all the numbers in a given list using Kotlin.