How to usenaive Method in Javascript
The naive approach would be a simple algorithm that repeatedly iterates through a set of numbers and tests each one to see if it is an Armstrong number. In this approach, a loop is used to get the digits of the number and then the sum is calculated as the sum of the nth power of each digit.
Example: This example implements the naive Method for verifying the Armstrong number.
Javascript
function isArmstrong(number) { let temp = number; let o = order(temp) let sum = 0; // Loop until temp is greater than 0 while (temp) { remainder = temp % 10; // Floor value of the quotient temp = Math.floor(temp / 10); sum = sum + Math.pow(remainder, o); } if (sum === number) { console.log(number + " is an Armstrong Number" ); } else { console.log(number + " is Not an Armstrong Number" ); } } // Function to calculate number of digits function order(number) { let n = 0; while (number > 0) { n++; number = Math.floor(number / 10); } return n; } // Input value 153 isArmstrong(153); // Input value 520 isArmstrong(520); |
153 is an Armstrong Number 520 is Not an Armstrong Number
JavaScript Program for Armstrong Numbers
In this article, we will see a JavaScript program to check whether the given number is an Armstrong number or not.
An Armstrong Number is an n-digit number that is the sum of the nth power of its all digits. For instance, Consider a 3-digit number, i.e., 153, which is a 3-digit number, & the sum of the cube of all its digits will be the number itself, i.e. 153.
13 = 1
53 = 5*5*5 = 125
33 = 3*3*3 = 27
13 + 53 + 33 = 1+125+27 = 153
To generalize it to a particular syntax form, then the following syntax will be used:
abcd… = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n)+....
Here a,b,c,d,… denotes the Base number & n denotes the exponent number.
Several methods can be used to check if a number is an Armstrong number or not, which are listed below:
Table of Content
- Using toString() and split() Method
- Using naive Method
- Using Array.from() Method
- Using Array Reduce
Contact Us