# Kotlin Program to Check Armstrong Number between Two Integers

Kotlin Server Side ProgrammingProgramming

#### Kotlin Online Training

68 Lectures 4.5 hours

#### Kotlin Masterclass Programming: Android Coding Bible

71 Lectures 5.5 hours

#### Android Dependency Injection using Dagger with Kotlin

18 Lectures 1.5 hours

In this article, we will understand how to display the Armstrong numbers between the given two numbers in Kotlin. An Armstrong number is a number that is equal to the sum of the cubes of its own digits. For example, 153 is

153 = (1)3 + (5)3 + (3)3


Below is a demonstration of the same

Suppose our input is

1 & 500


The desired output would be

The Armstrong numbers between 1 and 500 are 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407


## Algorithm

• Step 1 − Start

• Step 2 − Declare four integers: inputLow, inputHigh, originalNumber and myResult

• Step 3 − Define inputLow and inputHigh values

• Step 4 − Read the values

• Step 5 − Run a for loop to generate Armstrong numbers using %, / and * operator

• Step 6 − Divide by 10 and get remainder for ‘originalNumber’.

• Step 7 − Multiply ‘remainder’ thrice, and add to ‘myResult’, and make that the current ‘myResult’.

• Step 8 − Divide ‘originalNumber’ by 10, and make that the current ‘originalNumber’.

• Step 9 − Display the result

• Step 10 − Stop

## Example 1

In this example, we will check Armstrong Number between two integers in Kotlin. First, declare and set two variables. This is the range within which we will find the Armstrong Numbers −

val inputLow = 1
val inputhigh = 500


Now, use the while loop inside for loop to find the Armstrong numbers in a range

for (number in inputLow + 1..inputhigh - 1) {
var tempDigits = 0
var myResult = 0
var originalNumber = number

while (originalNumber != 0) {
originalNumber /= 10
++tempDigits
}

originalNumber = number

while (originalNumber != 0) {
val remainder = originalNumber % 10
myResult += Math.pow(remainder.toDouble(), tempDigits.toDouble()).toInt()
originalNumber /= 10
}


Let us now see the complete example to find the Armstrong Numbers

fun main() {
val inputLow = 1
val inputhigh = 500
println("The lower and higher limit are defined as $inputLow and$inputhigh ")
println("The Armstrong numbers are:")

for (number in inputLow + 1..inputhigh - 1) {
var tempDigits = 0
var myResult = 0
var originalNumber = number

while (originalNumber != 0) {
originalNumber /= 10
++tempDigits
}
originalNumber = number

while (originalNumber != 0) {
val remainder = originalNumber % 10
myResult += Math.pow(remainder.toDouble(), tempDigits.toDouble()).toInt()
originalNumber /= 10
}

if (myResult == number)
}
}


## Output

The lower and higher limit are defined as 1 and 500
The Armstrong numbers are:
2 3 4 5 6 7 8 9 153 370 371 407

Updated on 13-Oct-2022 12:49:28

Advertisements