English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of Kotlin Examples
In this program, you will learn to check if a given number is an Armstrong number. You will learn how to do this by using a while loop in Kotlin.
A positive integer is called an Armstrong number if
abcd... = an + bn + cn + dn + ...
For3An Armstrong number of n digits, the sum of the cubes of each digit equals the number itself. For example:
153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong number.
fun main(args: Array<String>) { val number = 371 var originalNumber: Int var remainder: Int var result = 0 originalNumber = number while (originalNumber != 0) { remainder = originalNumber % 10 result +result = Math.pow(remainder.toDouble(), 3.0).toInt() originalNumber /= 10 } if (result == number) println("$number is an Armstrong number.") else println("$number is not an Armstrong number.") }
When the program is run, the output is:
371 is an Armstrong number
First, the value of the given number (number) is stored in another integer variable originalNumber. This is because we need to compare the final number with the original number's value at the end.
Then, use a while loop to traverse originalNumber until it equals 0.
In each iteration, the last digit of num is stored in remainder.
Then, add remainder by using the Math.pow() function3(number of digits)and add it to result.
Then, divide by10Then, remove the last digit from originalNumber.
Finally, compare result and number. If they are equal, then it is an Armstrong number. If not, it is not.
The equivalent Java code is as follows:Java program to check Armstrong number
fun main(args: Array) { val number = 1634 var originalNumber: Int var remainder: Int var result = 0 var n = 0 originalNumber = number while (originalNumber != 0) { originalNumber /= 10 ++n } originalNumber = number while (originalNumber != 0) { remainder = originalNumber % 10 result +result = Math.pow(remainder.toDouble(), n.toDouble()).toInt() originalNumber /= 10 } if (result == number) println("$number is an Armstrong number.") else println("$number is not an Armstrong number.")
In this program, we used two while loops. The first while loop is used to calculate the number of digits in number.
Then, originalNumber is restored to the given number.
Then, the second while loop checks if the number is an Armstrong number.
Visit this page to learn howDisplay All Armstrong Numbers Between Two Time Intervals.