In this tutorial, you shall learn how to write a program to find the factors of a given number in Kotlin.

Kotlin – Find Factors of a Number

To find the factors of a given number in Kotlin, iterate over the range from 1 to given number, and check if the integer in the range can exactly divide the given number. If it can, then that integer is a factor, else not.

Program

In the following program, we read a number from user and store it in num, then find the factors of this number.

Main.kt

</>
Copy
fun findFactors(number: Int) {
    println("Factors of $number are: ")
    for (i in 1..number) {
        if (number % i == 0) {
            print("$i ")
        }
    }
}

fun main() {
    print("Enter an integer : ")
    val num = readLine()!!.toInt()
    findFactors(num)
}

Output #1

Enter an integer : 120
Factors of 120 are: 
1 2 3 4 5 6 8 10 12 15 20 24 30 40 60 120 

Output #2

Enter an integer : 451
Factors of 451 are: 
1 11 41 451 

Related tutorials for the above program

Program with Fewer Iterations

If i is a factor of n, then n/i is also a factor. Taking this fact into consideration, we can just reduce the iterations at a logarithmic scale.

In the following program, we find the factors of the given number using While loop with fewer iterations than the previous program.

Main.kt

</>
Copy
fun findFactors(number: Int) {
    println("Factors of $number are: ")
    var i = 1
    while (i <= number/i) {
        if (number % i == 0) {
            print("$i ")
            val anotherFactor = number/i
            print("$anotherFactor ")
        }
        i++
    }
}

fun main() {
    print("Enter an integer : ")
    val num = readLine()!!.toInt()
    findFactors(num)
}

Output #1

Enter an integer : 120
Factors of 120 are: 
1 120 2 60 3 40 4 30 5 24 6 20 8 15 10 12 

Output #2

Factors of 451 are: 
1 451 11 41 

Related tutorials for the above program

Conclusion

In this Kotlin Tutorial, we learned how to find the factors of a given number using For loop or While loop.