Write a Kotlin Program to Check Armstrong Number

In Kotlin, an Armstrong number is a number that is equal to the sum of its digits raised to the power of the number of digits.

For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153.

To check whether a number is an Armstrong number or not, we need to follow these steps:

  1. Take an integer input from the user.
  2. Find the number of digits in the input number.
  3. Calculate the sum of each digit raised to the power of the number of digits.
  4. Compare the sum with the original number.
  5. If the sum is equal to the original number, then the number is an Armstrong number. Otherwise, it is not.

Let’s write a Kotlin program to implement this algorithm:

fun main() {
    print("Enter a number: ")
    val num = readLine()!!.toInt()
    var originalNum = num
    var digits = 0
    var sum = 0

    // Find the number of digits in the input number
    while (originalNum != 0) {
        originalNum /= 10
        ++digits
    }

    originalNum = num

    // Calculate the sum of each digit raised to the power of the number of digits
    while (originalNum != 0) {
        val remainder = originalNum % 10
        sum += Math.pow(remainder.toDouble(), digits.toDouble()).toInt()
        originalNum /= 10
    }

    // Compare the sum with the original number
    if (sum == num)
        println("$num is an Armstrong number.")
    else
        println("$num is not an Armstrong number.")
}

In the above program, we first take an integer input from the user using the readLine() function. We then initialize three variables – originalNum, digits, and sum.

In the first while loop, we find the number of digits in the input number by dividing the originalNum by 10 until it becomes 0.

In the second while loop, we calculate the sum of each digit raised to the power of the number of digits using the Math.pow() function.

We then divide the originalNum by 10 to remove the last digit.

Finally, we compare the sum with the original number to determine whether it is an Armstrong number or not.

We use the if-else statement to print the output accordingly.

In conclusion, the above program is a simple and efficient way to check whether a number is an Armstrong number or not in Kotlin.