Kotlin Class: MathUtils class with static functions
Kotlin Class: Exercise-13 with Solution
Write a Kotlin program that creates a class 'MathUtils' with static functions to calculate the factorial, square root, and cube root of a number.
Sample Solution:
Kotlin Code:
class MathUtils {
companion object {
fun factorial(n: Int): Long {
if (n == 0 || n == 1) {
return 1
}
var result = 1L
for (i in 2..n) {
result *= i
}
return result
}
}
}
fun sqrt(n: Double): Double {
return Math.sqrt(n)
}
fun cbrt(n: Double): Double {
return Math.cbrt(n)
}
fun main() {
val number = 7
val factorial = MathUtils.factorial(number)
println("Factorial of $number is: $factorial")
val squareRoot = sqrt(number.toDouble())
println("Square root of $number is: $squareRoot")
val cubeRoot = cbrt(number.toDouble())
println("Cube root of $number is: $cubeRoot")
}
Sample Output:
Factorial of 7 is: 5040 Square root of 7 is: 2.6457513110645907 Cube root of 7 is: 1.9129311827723892
Explanation:
In the above exercise -
- First we define a class "MathUtils" and declare a "companion" object inside it. The companion object contains static functions. Inside the companion object, we define a function "factorial()" to calculate the factorial of a number using an iterative approach.
- We also define top-level functions "sqrt()" and "cbrt()" outside the "MathUtils" class. These functions use the Math.sqrt and Math.cbrt functions from the standard library to calculate the square root and cube root of a number, respectively.
- In the "main()" function, we calculate the factorial of a number using the MathUtils.factorial function. We also calculate the square root and cube root using the sqrt and cbrt top-level functions, respectively.
Kotlin Editor:
Previous: Create Customer class and send welcome email.
Next: Shape, circle, and rectangle classes with area calculation.
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://w3resource.com/kotlin-exercises/class/kotlin-class-exercise-13.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics