Armstrong number in JavaScript

Armstrong number is a number that is equal to the sum of the nth power of each digit is equal to the given number.

For example:

153, 1634 is amrstrong number. because 13+53+33=153

153=1*1*1+5*5*5+3*3*3 for 3 digits

14+64+34+44=1634 for four digit

Logic to find Armstrong number of three digits

  • Take input from the user and stored it in a variable n.
  • Copy the value of n into the copy variable, for later comparing whether number Armstrong or not.
  • Iterate the loop until the value of the copy variable becomes 0 or less than zero.
  • Store the output of the loop into the sum variable.
  • Check user value i.e n is equal to the sum or not.
  • if it is equal then if statement will get executed and print “It is an Armstrong number”.
  • if it's not equal else part gets executed and prints “It is not an Armstrong number”.

Armstrong number of three digits in JavaScript

In this program, you will take input from users using a window prompt, and you will check whether the number is an Armstrong or not.

<!DOCTYPE html>
<html>
  <body>
   <script>
    function Armstrong() {
       var r,sum=0,n,copy;
        n = parseInt(prompt("enter a number:"));
	copy=n;
        while (copy>0) {
           r=copy%10;
   	   sum=sum+(r*r*r);
   	   copy=parseInt(copy/10);
        }
	if(n==sum)
	{
           document.write(n+" is a Armstrong number");
	}
	else
	{
	   document.write(n+" is not Armstrong a number");
	}
   }
    </script>
    <form>
      <input type="button" value="ArmstrongNo" onclick="Armstrong();" />
    </form>
  </body>
</html>
 
Run now

Input has taken through javascript prompt method

output

enter a number:153
153 is a Armstrong number

output

enter a number:123
123 is not Armstrong a number

Check Armstrong number of nth digits in JavaScript

In this program, you will take input from users using a window prompt, and you will check whether the nth digit number is an Armstrong or not.

<!DOCTYPE html>
<html>
  <body>
   <script>
    function Armstrong() {
        var r,sum=0,n,copy,countdigit=0;
       // take input from user
        n = parseInt(prompt("enter a number:"));
	copy=n;
	while(copy>0)
       { 
	     // count the number of digit
             countdigit++;
	     copy=parseInt(copy/10);
	}
        copy=n;
        while (copy>0) {
              r=copy%10;
	      // find the power of each individual digit
   	       sum=sum + Math.pow( r, countdigit );
   	       copy=parseInt(copy/10);
        }
	if(n==sum)   // Check whether the sum is equal to the given number or not
	{
       document.write(n+" is a Armstrong number");
	}
	else
	{
	   document.write(n+" is not Armstrong a number");
	}
   }
    </script>
    <form>
      <input type="button" value="ArmstrongNo" onclick="Armstrong();" />
    </form>
  </body>
</html> 
 

Input has taken through javascript prompt method

output

enter a number:1634
1634 is a Armstrong number