English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin Program to Display Number Factors

Comprehensive Collection of Kotlin Examples

In this program, you will learn how to use a for loop in Kotlin to display all the factors of a given number.

Example: Factors of a positive integer

fun main(args: Array<String>) {
    val number = 60
    print("$number's factors are:")
    for (i in 1..number) {
        if (number % i == 0) {
            print("$i ")
        }
    }
}

When the program is run, the output is:

60's factors are: 1 2 3 4 5 6 10 12 15 20 30 60

In the above program, the number that will be found to have factors is stored in the variable number(60) to.

for loop from1Iterate up to number. In each iteration, check if number is divisible by i (the condition is that i is a factor of number), and increase the value of i1.

The following is the equivalent Java code:Java Program to Display Factors of a Number

Comprehensive Collection of Kotlin Examples