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

Kotlin program to calculate the power of a number

Comprehensive Collection of Kotlin Examples

In this program, you will learn to calculate the power of a number using and not using the pow() function.

Example1: Calculate the power of a number without using pow()

fun main(args: Array<String>) {
    val base = 3
    var exponent = 4
    var result: Long = 1
    while (exponent != 0) {
        result *= base.toLong()
        --exponent
    }
    println("Answer = $result")
}

When running this program, the output is:

Answer = 81

In this program, values are assigned to base and exponent separately3and4.

Using a while loop, we multiply result by base until the exponent (exponent) becomes zero.

In this case, we multiply result by the base a total of4times, so result= 1 * 3 * 3 * 3 * 3 = 81. We also need to convert the base to Long because result only accepts Long, and Kotlin focuses on type safety.

However, like Java, if the exponent is negative, the above code does not work. To do this, you need to use the pow() function in Kotlin.

This is equivalent Java code:Java program to calculate the power of a number

Example2: Calculate the power of a number using pow()

fun main(args: Array<String>) {
    val base = 3
    val exponent = -4
    val result = Math.pow(base.toDouble(), exponent.toDouble())
    println("Answer = $result")
}

When running this program, the output is:

Answer = 0.012345679012345678

In this program, we use the standard library function Math.pow() to calculate the power of the base.

We also need to convert base and exponent to Double because the pow function only accepts Double parameters.

Comprehensive Collection of Kotlin Examples