Find all the armstrong number between two numbers

An algorithm to find all the Armstrong numbers between the two numbers.

We will find all the Armstrong number between the two numbers in Javascript and print them.

Armstrong: When we cube each digit of the number and add, it should be equal to the given number.

Example

Input:
100 200
100 400
0   100

Output:
153

153
370
371

0
1

Implementation

  • We are going to loop through all the numbers between the given two numbers.
  • Then we will check if the current number is Armstrong or not and print it.
  • Everything will be written in ES6.
//function to check if given number is Armstrong or not
let isArmstrong = (num) => {
  let sum = 0;
  //store the actual number to check later
  let temp = num;

  //Extract each digit of number
  while(num > 0){
    //get the last digit of the number
    let d = parseInt(num % 10);
  
    //find the cube
    d = d ** 3;
    sum = sum + d;
  
    //reduce the number
    num = parseInt(num / 10);
  }
  
  //Check if number equals to the cubed sum
  return temp === sum;
}

//Function to print all the Armstrong number
let printArmstrong = (start, end) => {

  //loop through given range of numbers
  for(let i = start; i <= end; i++){

     //If the it is Armstrong then print
     if(isArmstrong(i)){
       console.log(i);
     }
  }
}
Input:
printArmstrong(0, 100);
printArmstrong(100, 200);
printArmstrong(300, 700);

Output:
0
1

0
1
153

370
371
407

Time complexity: O(n * d). where n is the difference between the two numbers and d is the no of digits in the biggest number.

Space complexity: O(1).

Time and Space complexity

  • We are going to loop through the given range of numbers that will take O(n) where n is the difference between the given numbers, Then we will be checking if the number is Armstrong or not that will take O(d) where d is the number of digits in the biggest number, so Time complexity is O(n * d).
  • We are using constant space, so Space complexity is O(1).

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *