JavaScript(JS) JS check armstrong number

www.ig‮aeditfi‬.com

An Armstrong number is a number that is equal to the sum of its digits raised to the power of the number of digits. To check if a given number is an Armstrong number in JavaScript, you can use a similar algorithm to the one used in the previous question. Here's an example:

function isArmstrongNumber(number) {
  let sum = 0;
  let numDigits = number.toString().length;

  let temp = number;
  while (temp > 0) {
    let digit = temp % 10;
    sum += Math.pow(digit, numDigits);
    temp = Math.floor(temp / 10);
  }

  return sum === number;
}

console.log(isArmstrongNumber(153)); // Output: true
console.log(isArmstrongNumber(371)); // Output: true
console.log(isArmstrongNumber(407)); // Output: true
console.log(isArmstrongNumber(123)); // Output: false

In the example above, we define a function isArmstrongNumber that takes one argument number, which is the number to check. The function initializes a variable sum to store the sum of the digits raised to the power of the number of digits. It also calculates the number of digits in the number using the toString() method and the length property.

The function then uses a while loop to iterate over each digit of the number and calculate the sum. It does this by using the modulo operator % to get the last digit of the number and the Math.pow() method to raise the digit to the power of the number of digits. It then updates the sum variable and the temp variable, which is used to keep track of the remaining digits.

Finally, the function checks if the sum variable is equal to the original number. If it is, then the function returns true, indicating that the number is an Armstrong number. Otherwise, it returns false.

In the example above, we call the isArmstrongNumber function with several test cases to demonstrate how it works. The function correctly identifies the Armstrong numbers 153, 371, and 407 as true and the non-Armstrong number 123 as false.