Armstrong Number in C++
Written by
Armstrong number in C++ Program
An Armstrong number is a number which is equal to the sum of digits raise to the power total number of digits in the number.
Examples of Armstrong number :
0, 1, 2, 3, 153, 370, 407, 1634
0 = 01 = 0
1 = 11 = 1
153 = 13 + 53 + 33 = 153
370 = 33 + 73 + 03 = 370
1634 = 14 + 64 + 34+ 44
Logic:
First, we’ll count the number of digits in the given number. Then, we’ll calculate the power of each digit and store the sum of digits. If the sum is the same as the original number, then, the number is called Armstrong number.
Algorithm:
- Run a for loop to find the number of digits in the number.
- Create a function to calculate the product of the digit raised to the power.
- Add the calculated product to the final sum.
- Compare the original number with the final sum and output accordingly.
Code:
#include<iostream>
using namespace std;
int calc(int n, int power)
{
int product=1;
for(int i=0;i<power;i++)
{
product*=n;
}
return product;
}
int main()
{
int i,count=0,rem,sum=0;
cout<<"Enter a number";
cin>>i;
int num=i;
//count digits in number
while(i>0)
{
i=1/10;
count++;
}
i=num;
while(i>0)
{
rem=i%10;
sum=sum+calc(rem,count);//calculate power of rem
i=i/10;
}
if(num==sum)
cout<<"\nArmstrong number!";
else
cout<<" \n Not an Armstrong Number!";
return 0;
}
Output:
Enter a number 3
Armstrong number!