Kotlin – Find All Factors of a Number
In this tutorial, you’ll learn how to find all the factors of a given number using Kotlin.
In Kotlin, you can achieve this by using a loop to iterate through possible divisors and checking if they evenly divide the given number. The factors are those divisors that yield a remainder of zero.
Finding Factors of a Positive Integer
We’ll start with an example of finding all the factors of a positive integer.
We write a function findFactors() that takes a number as argument, and prints all the factors of this given number.
Kotlin Program
// Function to find factors of a number
fun findFactors(number: Int) {
println("Factors of $number:")
for (i in 1..number) {
if (number % i == 0) {
println(i)
}
}
}
fun main() {
val number = 12
findFactors(number)
}
Output
Factors of 12:
1
2
3
4
6
12
Summary
In this Kotlin Tutorial, we learned how to find all the factors of a given number.