Write a program in C++ & Python for Armstrong Number

By | July 2, 2019

An Armstrong is an n digits number whose sum of digit raised to the power n is equal to itself.

For example, 153 is an Armstrong number because it is a 3-digit number and sum of each digit raised to the power 3 is equal to 153.

(1)3 +(5)3 +(3)3 = 1+125+27 = 153

C++:

#include<iostream.h>
#include< conio.h>
#include<stdio.h>
#include<math.h>

void main()
{
clrscr();
int num, m=0, power=0, x,temp;
cout<<"Enter a Number: ";
cin>>num;
temp = num;
while(temp!=0)
{
  temp = temp/10;
  power++;
}
temp = num;
while(num!=0)
{
  x =num%10;
  m+= pow(x,power);
  num= num/10;
}
if(temp == m)
cout<<temp <<" is an Armstrong number";
else
cout<<temp <<" is not an Armstrong number";
getch();
}

Output

Enter a number: 54748
54748 is an Armstrong number

Python:

num = int(input("Enter a number: "))
temp = num
power = 0
m = 0
while(temp!=0):
                temp = temp//10
                power += 1
temp = num
while(num!=0):
                x = num%10
                m += x**power
                num = num//10

if temp==m:
                print(temp,"is an Armstrong number")

else:
                print(temp,"is not an Armstrong number")

 

Output

Enter a number: 153
153 is an Armstrong number

Leave a Reply

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