# Kotlin Program to Find nth Armstrong Number

###### Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners. Also, if you are interested in content writing, you can mail us at tutorialwing@gmail.com.

Write a Kotlin Program to Find nth Armstrong Number

### What is Armstrong Number ?

A positive integer (x) of n digits is called armstrong number of order n (number of digits in x) if

```abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + ....
```

Note that abcd… is number x where a, b, c, d ….etc. are it’s digits. n is number of digits in x.

For example,

```Input:
9

Output:
9th armstrong number is 9

```
```Input:
10

Output:
10th armstrong number is 153
```
```Input:
15

Output:
15th armstrong number is 8208
```

## 1. Program to Find nth Armstrong Number

Sourcecode –

```import java.util.*
import kotlin.math.floor
import kotlin.math.log10
import kotlin.math.pow
import kotlin.math.roundToInt

fun main() {

println("Enter n:")

if(n < 1)
return

var count = 0
var armN = 0

// Run a loop from 1 to INT_MAX to find nth Armstrong number
for(i in 1..Int.MAX_VALUE) {
if(checkArmstrong((i))) {
count++
}
if(count == n) {
armN = i
break
}
}

if(armN != 0) {
println("" + n + "th armstrong number is \$armN")
} else {
println("No " + n + "th armstrong number")
}
}

private fun checkArmstrong(number: Int): Boolean {

// Get the count of digits in number
val n = floor(log10(number.toDouble()) + 1).roundToInt()

var x = number

// Find sum by power last digit in n to count.
var sum = 0
while(x > 0) {
val digit = x % 10
sum = (sum + (digit.toDouble().pow(n))).roundToInt()
x /= 10
}

// Return true if sum is equal to number
return sum == number
}
```

When you run the program, output will be –

```Enter n:
14
14th armstrong number is 1634
```
###### Explanation:

Here, we have created an object of Scanner. Scanner takes an argument which says where to take input from.
System.`in` means take input from standard input – Keyboard.

read.nextIn() means read anything entered by user before space or line break from standard input – Keyboard.

Run a loop from 1 to maximum possible value.
Check for each value (i) if it is an armstrong number. If yes, increase the count.
Compare if count is equal to number n (entered by user). If yes, return value of i.

Thus, we went through Kotlin Program to Find nth Armstrong Number.