Kotlin program to check Armstrong number

Kotlin | Check Armstrong Number: Here, we are going to learn how to check whether a given number is an Armstrong number or not in Kotlin programming language? Submitted by IncludeHelp, on April 22, 2020

Armstrong number

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 an integer number N, we have to check whether it is an Armstrong number or not.

Example:

Input:
N = 153

Output:
153 is an Armstrong Number

Input:
N = 234

Output:
234 is not an Armstrong Number

Program to check Armstrong number in Kotlin

/**
 * Kotlin Program to check Given number  is an Armstrong Number or not
*/
 
package com.includehelp.basic

import java.util.*

// Function for check Armstrong Number
fun isArmStrongNo(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>) {
    val sc = Scanner(System.`in`)

    // Input Integer Number
    println("Enter Number  : ")
    val num: Long = sc.nextLong()

    // Call function to check number is Armstrong or not
    if (isArmStrongNo(num))   
		println("$num is an Armstrong Number") 
	else  
		println("$num is not an Armstrong Number")
}

Output

RUN 1:
Enter Number  :
153
153 is an Armstrong Number
---
RUN 2:
Enter Number  :
234
234 is not an Armstrong Number
---
RUN 3:
Enter Number  :
23444
23444 is not an Armstrong Number
---
RUN 4:
Enter Number  :
1634
1634 is an Armstrong Number
----
RUN 5:
Enter Number  :
9474
9474 is an Armstrong Number

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.