Home »
Kotlin »
Kotlin Programs »
Kotlin Basic Programs
Kotlin program to display Armstrong numbers between a range
Kotlin | Armstrong numbers between a range: Here, we are going to learn how to find and display Armstrong numbers between given range in Kotlin programming language?
Submitted by IncludeHelp, on April 22, 2020
Kotlin - Display Armstrong numbers between a range
An Armstrong number is a number such that the sum of the nth power of its digits is equal to the number itself, where n is the number of digits in the number (taken here to mean positive integer).
abcd = a^n + b^n + c^n + d^n
Problem statement
Given two numbers start and end, we have to display the list of Armstrong numbers between start and end.
Example:
Input:
start = 15
end = 700
Output:
[153, 370, 371, 407]
Program to display Armstrong numbers between a range in Kotlin
/**
* Kotlin Program to check find out ArmStrong number
* between given Range(include START and END)
*/
package com.includehelp.basic
import java.util.*
// Function for check Armstrong number
fun findArmStrongNo(number: Long): Boolean {
var isArmNumber = false
var result : Long= 0
var original = number
//Count No Digits in numbers
val digits = original.toString().length
while (original > 0) {
val r = original % 10
result +=Math.pow(r.toDouble(), digits.toDouble()).toLong()
original /= 10
}
if (result == number) {
isArmNumber = true
}
return isArmNumber
}
//Main Function, Entry Point of Program
fun main(arg: Array<String>) {
//Input Stream
val sc = Scanner(System.`in`)
//Input Start of Range
print("Enter Start of Range : ")
val start: Long = sc.nextLong()
//Input End of Range
print("Enter End of Range : ")
val end: Long = sc.nextLong()
//Declare Mutable List to hold factors
val list: MutableList<Long> = ArrayList()
//iterate through loop start to end to find ArmStrong in Range
for (i in start..end) {
if (findArmStrongNo(i)) {
list.add(i)
}
}
println("Armstrong Numbers from $start to $end : $list")
}
Output
RUN 1:
Enter Start of Range : 15
Enter End of Range : 700
Armstrong Numbers from 15 to 700 : [153, 370, 371, 407]
---
RUN 2:
Enter Start of Range : 99
Enter End of Range : 999999
Armstrong Numbers from 99 to 999999 : [153, 370, 371, 407, 1634, 8208, 9474, 54748, 92727, 93084, 548834]