# Kotlin function: Calculate the sum of arithmetic or geometric series

## Kotlin Function: Exercise-22 with Solution

Write a Kotlin function that calculates the sum of a given arithmetic or geometric series. The function should take the first term, common difference/ratio, and the number of terms as arguments. Use generic types to handle both arithmetic and geometric series.

**Sample Solution:**

**Kotlin Code:**

```
fun <T : Number> calculateSeriesSum(firstTerm: T, commonDiffRatio: T, numTerms: Int): Double {
require(numTerms > 0) { "Number of terms must be greater than 0." }
val a = firstTerm.toDouble()
val n = numTerms.toDouble()
return when (commonDiffRatio) {
is Double -> {
val r = commonDiffRatio
if (r == 1.0) {
a * n
} else {
a * (1 - Math.pow(r, n)) / (1 - r)
}
}
is Int -> {
val d = commonDiffRatio
if (d == 0) {
a * n
} else {
(n / 2) * (2 * a + (n - 1) * d)
}
}
else -> throw IllegalArgumentException("Unsupported data type for common difference/ratio.")
}
}
fun main() {
val arithmeticSum = calculateSeriesSum(2, 3, 5)
println("Arithmetic Sum: $arithmeticSum")
val geometricSum = calculateSeriesSum(2.0, 3.0, 5)
println("Geometric Sum: $geometricSum")
}
```

Sample Output:

Arithmetic Sum: 40.0 Geometric Sum: 242.0

**Explanation:**

In the above exercise -

- The "calculateSeriesSum()" function is defined with a generic type parameter T, constrained to Number, indicating that the function can accept any numeric type.
- The function takes three parameters: firstTerm (the first term of the series), commonDiffRatio (the common difference for arithmetic series or common ratio for geometric series), and numTerms (the number of terms in the series).
- The require function ensures that the numTerms parameter is greater than 0. If it is not, an exception is thrown with the specified error message.
- The firstTerm and numTerms parameters are converted to Double using the toDouble() function for precise calculations.
- The function uses a when expression to handle different types of commonDiffRatio (Double or Int) and perform the respective calculations for arithmetic and geometric series.
- For a Double commonDiffRatio, it checks if the ratio is equal to 1.0. If so, it returns the product of the first term and the number of terms (a n). Otherwise, it calculates the sum using the formula (a (1 - Math.pow(r, n))) / (1 - r).
- For an Int commonDiffRatio, it checks if the difference is equal to 0. If so, it returns the product of the first term and the number of terms (a n). Otherwise, it calculates the sum using the formula (n / 2) (2 a + (n - 1) d).
- If the commonDiffRatio is neither Double nor Int, it throws an exception indicating that the data type is not supported.
- In the "main()" function, the "calculateSeriesSum()" function is called twice: once for an arithmetic series (calculateSeriesSum(2, 3, 5)) and once for a geometric series (calculateSeriesSum(2.0, 3.0, 5)).
- The calculated sums are then printed using println.

**Kotlin Editor: **

**Previous:** Calculate the square of a number.

**What is the difficulty level of this exercise?**

Test your Programming skills with w3resource's quiz.

**It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.**

https://www.w3resource.com/kotlin-exercises/function/kotlin-function-exercise-22.php

**Weekly Trends and Language Statistics**- Weekly Trends and Language Statistics