An Armstrong number is a number that is equal to the sum of its own digits raised to the power of the number of digits.
For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153.
In this tutorial, we will discuss how to write a JavaScript program to find Armstrong numbers in an interval.
To find Armstrong numbers in an interval, we need to first understand the steps involved in checking if a number is an Armstrong number.
We need to find the number of digits in the number, raise each digit to the power of the number of digits, sum the results, and compare the result with the original number.
If they are equal, the number is an Armstrong number.
Now let’s see how to implement this in JavaScript to find Armstrong numbers in an interval.
function findArmstrongNumbers(start, end) { let armstrongNumbers = []; for (let i = start; i <= end; i++) { let number = i; let sum = 0; let numOfDigits = number.toString().length; while (number > 0) { let digit = number % 10; sum += Math.pow(digit, numOfDigits); number = Math.floor(number / 10); } if (sum === i) { armstrongNumbers.push(i); } } return armstrongNumbers; }
In the above code, we have defined a function findArmstrongNumbers that takes two arguments start and end, which represent the start and end of the interval, respectively.
The function then initializes an empty array armstrongNumbers to store the Armstrong numbers found in the interval.
We then loop through each number in the interval using a for loop. Inside the loop, we first create a variable number to hold the current number being checked, a variable sum to hold the sum of the digits raised to the power of the number of digits, and a variable numOfDigits to hold the number of digits in the current number.
We then use a while loop to loop through each digit in the number. Inside the loop, we first calculate the last digit of the number using the modulo operator %, and then raise it to the power of the number of digits using the Math.pow function.
We add this result to the sum variable, and then remove the last digit from the number using integer division Math.floor(number / 10).
After the while loop has finished, we check if the sum variable is equal to the original number i. If they are equal, we push the number to the armstrongNumbers array.
Finally, we return the armstrongNumbers array, which contains all the Armstrong numbers found in the interval.
To use this function, we can simply call it with the start and end of the interval as arguments, like this:
let start = 100; let end = 999; let armstrongNumbers = findArmstrongNumbers(start, end); console.log(armstrongNumbers);
This will find all the Armstrong numbers between 100 and 999 and log them to the console.
In conclusion, the above JavaScript program provides an easy way to find Armstrong numbers in an interval.