In this tutorial, you shall learn how to write a program to check if a given number is an Armstrong number in Kotlin.
Kotlin – Armstrong Number
To check if a number is an Armstrong number in Kotlin, check the equality of given number and the sum of individual digits raised to the power of the length of the number.
For example if abcd...
is given number, then this number is an Armstrong number if the following condition returns true.
abcd... == a^n + b^n + c^n + d^n + ...
where n
is length of the number abcd...
, and a^n
is the digit a
in the number raised to the power of n
.
Program
In the following program, we read an integer number from user into variable num
, and check if this number is an Armstrong number or not by computing the sum of powers of individual digits, and equating the result to the original number.
Main.kt
import kotlin.math.pow
fun main() {
print("Enter an integer : ")
val number = readLine()!!.toInt()
val length = number.toString().length
var sum = 0
var temp = number
while (temp > 0) {
val digit = temp % 10
sum += digit.toDouble().pow(length.toDouble()).toInt()
temp /= 10
}
if (number == sum) {
println("$number is an Armstrong number.")
} else {
println("$number is not an Armstrong number.")
}
}
Output #1
Enter an integer : 153
153 is an Armstrong number.
Output #2
Enter an integer : 12354
12354 is not an Armstrong number.
Output #3
Enter an integer : 92727
92727 is an Armstrong number.
You can also check for other Armstrong numbers: 1634, 8208, 9474, 54748, 92727, 93084, 548834, 1741725, 4210818, 9800817, 9926315, etc.
Conclusion
In this Kotlin Tutorial, we learned how to check if given number is an Armstrong number or not.