Q:

Kotlin program to display Armstrong numbers between a range

belongs to collection: Kotlin Basic Programs

0

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

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]

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Kotlin Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Kotlin program to check given number is palindrome... >>
<< Kotlin program to check Armstrong number...