JavaScript Code


How to check if a number is Armstrong?


Armstrong Number Program

In this tutorial, you are given a number. Write JavaScript program to check if given number is Armstrong number or not.

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

In the following program, given an n-digit number in num, 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.