JavaScript Code

How to check if a number is Armstrong?


Problem Statement

given a number, write JavaScript program to check if given number is Armstrong number or not

Solution

an n-digit number abcd.. is said to be an Armstrong number if it obeys the following condition

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

we write a function isArmstrong() that takes the given number as argument and return true if the number is Armstrong, or false otherwise

inside the function we compute the sum of powers (as in the above equation), and compare it with the original number

to find the value of a raised to the power n, use Math.pow() function

Program

given an n-digit number, check if it is an Armstrong number

function isArmstrong(num) {
    num = new String(num);
    let n = num.length;
    let result = 0;
    //compute pow(a,n)+pow(b,n)+...
    for ( let index = 0; index < num.length; index++ ) {
        let digit = parseInt(num[index]);
        result += Math.pow(digit, n);
    }
    //check if given number equals expansion
    if( parseInt(num) == result ) {
        return true;
    } else {
        return false;
    }
}

let num = 153;
let result = isArmstrong(num);
console.log(`is ${num} an armstrong number? ${result}`);

we converted given number to string because we needed to work with individual digits, length, etc.