English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of Kotlin Examples
In this program, you will learn to use Kotlin functions to display all Armstrong numbers between two given intervals (low and high).
To find all Armstrong numbers between two integers, the function checkArmstrong() will be created. This functionCheck if a number is an Armstrong number.
fun main(args: Array<String>) { val low = 999 val high = 99999 for (number in low + 1..high - 1) { if (checkArmstrong(number)) print("$number ") } } fun checkArmstrong(num: Int): Boolean { var digits = 0 var result = 0 var originalNumber = num //Digit Calculation while (originalNumber != 0) { originalNumber /= 10 ++digits } originalNumber = num //The result includes the n-th power of its digits while (originalNumber != 0) { val remainder = originalNumber % 10 result +The result is obtained by taking the n-th power of the digits and converting it to an integer. originalNumber /= 10 } if (result == num) return true return false }
When the program is run, the output is:
1634 8208 9474 54748 92727 93084
In the above program, we created a function named checkArmstrong(), which accepts a parameter num and returns a boolean value.
If the number isArmstrongif it returns true. Otherwise, it returns false.
According to the return value, the number will be printed on the screen within the main() function.
This is the equivalent Java code:Check Using FunctionArmstrongJava Program for Numbers.