To find all armstrong numbers between two integers, checkArmstrong()
function is created. This function checks whether a number is armstrong or not.
Example: Armstrong Numbers Between Two Integers
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
// number of digits calculation
while (originalNumber != 0) {
originalNumber /= 10
++digits
}
originalNumber = num
// result contains sum of nth power of its digits
while (originalNumber != 0) {
val remainder = originalNumber % 10
result += Math.pow(remainder.toDouble(), digits.toDouble()).toInt()
originalNumber /= 10
}
if (result == num)
return true
return false
}
When you run the program, the output will be:
1634 8208 9474 54748 92727 93084
In the above program, we've created a function named checkArmstrong()
which takes a parameter num and returns a boolean value.
If the number is armstrong, it returns true
. If not, it returns false
.
Based on the return value, number is printed on the screen inside main()
function.
Here's the equivalent Java code: Java Program to Check Armstrong Number using Function.