Kotlin – Check if a Number is Armstrong
In this tutorial, you’ll learn how to determine whether a given number is an Armstrong number or not using Kotlin.
An Armstrong number is a number that is equal to the sum of its own digits, each raised to the power of the number of digits in the number itself. In other words, an n-digit number is considered an Armstrong number if the sum of its digits, each raised to the power of n, equals the original number.
For example, let’s take the 3-digit number 153. Each digit raised to the power of 3: 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153. Therefore 153 is an Armstrong number.
Examples
Let’s explore examples to understand how to check if a number is an Armstrong number.
Checking if a 3-Digit Number is Armstrong
We’ll start with an example of checking if a 3-digit number is an Armstrong number.
Kotlin Program
import kotlin.math.pow
// Function to check if a number is an Armstrong number
fun isArmstrongNumber(number: Int): Boolean {
val digits = number.toString().map { it.toString().toInt() }
val numberOfDigits = digits.size
val sum = digits.map { it.toDouble().pow(numberOfDigits).toInt() }.sum()
return sum == number
}
fun main() {
val number = 153
val result = isArmstrongNumber(number)
if (result) {
println("$number is an Armstrong number.")
} else {
println("$number is not an Armstrong number.")
}
}
Output
153 is an Armstrong number.
In this example, we define a function isArmstrongNumber()
that checks whether the given number is an Armstrong number. The function converts the number into its digits, calculates the sum of the digits raised to the power of the number of digits, and compares it with the original number.
Checking if a 4-Digit Number is Armstrong
Here’s another example of checking if a 4-digit number is an Armstrong number.
Kotlin Program
import kotlin.math.pow
// Function to check if a number is an Armstrong number
fun isArmstrongNumber(number: Int): Boolean {
val digits = number.toString().map { it.toString().toInt() }
val numberOfDigits = digits.size
val sum = digits.map { it.toDouble().pow(numberOfDigits).toInt() }.sum()
return sum == number
}
fun main() {
val number = 1634
val result = isArmstrongNumber(number)
if (result) {
println("$number is an Armstrong number.")
} else {
println("$number is not an Armstrong number.")
}
}
Output
1634 is an Armstrong number.
In this example, we use the same isArmstrongNumber()
function to check if the 4-digit number 1634
is an Armstrong number.
Summary
In this Kotlin Tutorial, we learned how to check if a given number is an Armstrong number or not, with the help of example programs.