Kotlin Program to Display Factors of a Number

Finding the factors of a number is a common mathematical operation that is frequently required in programming tasks. Kotlin provides several ways to calculate and display the factors of a number efficiently. In this article, we’ll explore three Kotlin Program to Display Factors of a Number and their outputs.

1. Using Iterative Approach

This example demonstrates how to find and display the factors of a number using an iterative approach. We iterate from 1 to the given number, checking for factors along the way.

Code

Kotlin
fun main() {
    val number = 24
    println("Factors of $number:")
    for (i in 1..number) {
        if (number % i == 0) {
            println(i)
        }
    }
}

Output

Kotlin
Factors of 24:
1
2
3
4
6
8
12
24

2. Using Optimized Iterative Approach

In this example, we optimize the iterative approach by iterating only up to the square root of the given number. This reduces the number of iterations required, making the process more efficient for large numbers.

Code

Kotlin
import kotlin.math.sqrt

fun main() {
    val number = 36
    println("Factors of $number:")
    for (i in 1..sqrt(number.toDouble()).toInt()) {
        if (number % i == 0) {
            println(i)
            if (i != number / i) {
                println(number / i)
            }
        }
    }
}

Output

Kotlin
Factors of 36:
1
36
2
18
3
12
4
9
6

3. Using Functional Approach

Here, we use a functional programming approach to find and display the factors of a number. We generate a list of factors using the filter function and then print the list.

Code

Kotlin
fun main() {
    val number = 48
    val factors = (1..number).filter { number % it == 0 }
    println("Factors of $number:")
    factors.forEach { println(it) }
}

Output

Kotlin
Factors of 48:
1
2
3
4
6
8
12
16
24
48

4. Conclusion

Displaying factors of a number is a fundamental mathematical operation, and Kotlin offers multiple approaches to accomplish this task efficiently. Whether using an iterative approach, an optimized iterative approach, or a functional programming approach, understanding these solutions enhances your Kotlin programming skills and prepares you for handling mathematical computations effectively in your applications. Each example presented here provides a unique insight into Kotlin’s versatility in solving mathematical problems, giving you the flexibility to choose the most suitable approach based on your specific requirements.