Finding Armstrong numbers in a given range in JavaScript


A number is called Armstrong number if the following equation holds true for that number: xy...z =xx +yy+...+zz, where n denotes the number of digits in the number.

For example:

153 is an Armstrong number because −

11 +55 +33 = 1 + 125 + 27 =153

We are required to write a JavaScript function that takes in two numbers, a range, and returns all the numbers between them that are Armstrong numbers (including them, if they are Armstrong)

Example

The code for this will be −

const isArmstrong = number => {
   let num = number;
   const len = String(num).split("").length;
   let res = 0;
   while(num){
      const last = num % 10;
      res += Math.pow(last, len);
      num = Math.floor(num / 10);
   };
   return res === number;
};
const armstrongBetween = (lower, upper) => {
   const res = [];
   for(let i = lower; i <= upper; i++){
      if(isArmstrong(i)){
         res.push(i);
      };
   };
   return res;
};
console.log(armstrongBetween(1, 400));

Output

The output in the console −

[
   1, 2, 3, 4, 5,
   6, 7, 8, 9, 153,
   370, 371
]

Updated on: 15-Oct-2020

386 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements