Kotlin Program to Calculate the Power of a Number

Example 1: Calculate 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 you run the program, the output will be:

Answer = 81

In this program, base and exponent are assigned values 3 and 4 respectively.

Using the while loop, we keep on multiplying result by base until exponent becomes zero.

In this case, we multiply result by base 4 times in total, so result = 1 * 3 * 3 * 3 * 3 = 81. We also need to cast base to Long because result only accepts Long and Kotlin focuses on type safety.

However, as in Java, above code doesn't work if you have a negative exponent. For that, you need to use pow() function in Kotlin

Here's the equivalent Java code: Java Program to calculate power of a number


Example 2: Calculate 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 you run the program, the output will be:

Answer = 0.012345679012345678

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

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

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges