Open In App

How to do Exponentiation in Scala?

Last Updated : 02 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

This article focuses on discussing implementing exponentiation in Scala. The math.pow() function from the scala.math package is used for exponentiation in Scala.

Syntax: 

val result = pow(base, exponent)

Basic Approach

Below is the Scala program to implement exponentiation:

Scala
//Scala Program to use Exponential
import scala.math.pow

// Base and exponent values
val base = 2
val exponent = 3

// Calculate exponentiation
val result = pow(base, exponent)

// Print the result
println(result)

Output:

8.0

Using BigDecimal

Below is the Scala program to implement exponentiation using BigDecimal:

Scala
//Scala Program to use Exponential
import scala.math.BigDecimal

val base = 3
val exponent = 4

val result = BigDecimal(base).pow(exponent)

println(result)

Output:

81

With Long Data Types

Below is the Scala program to implement exponentiation with long data types:

Scala
//Scala Program to use Exponential
import scala.math.BigDecimal

val base = 5L // Long data type
val exponent = 2

val result = BigDecimal(base).pow(exponent)

println(result)

Output:

25

Next Article
Article Tags :

Similar Reads