WAP to check a given number is armstrong or not
Objective
Write a C++ program to check if a given number is an Armstrong number.
Algorithm / Approach
- Read
nand make a temporary copy. - Use a
whileloop to count the total number ofdigits. - Reset the temporary copy to
n. - In a second
whileloop, extract each digit (rem = temp % 10). - Raise that digit to the power of the total digit count:
p = pow(rem, digits). - Add
pto a runningsum. - Check if the calculated
sumexactly equals the original numbern.
main.cpp
#include<iostream>
#include<math.h>
using namespace std;
int main() {
int n, temp, rem, p;
int sum =0, digits =0;
cout<<"Enter a Number : ";
cin>>n;
temp = n;
while(temp !=0) {
digits++;
temp = temp/10;
}
temp = n;
while(temp!=0) {
rem = temp%10;
p = pow(rem,digits);
sum = sum+p;
temp = temp/10;
}
if(n==sum)
cout<< n<<" is armstrong no.";
else
cout<< n<<" is not armstrong no.";
return 0;
}
Expected Output
Enter a Number : 123 123 is not armstrong no.
Explanation of the Program
- An Armstrong number (or Narcissistic number) is a number that is equal to the sum of its own digits, each raised to the power of the number of digits.
- For example, 153 has 3 digits. (1³ + 5³ + 3³) = (1 + 125 + 27) = 153. Because it matches, 153 is an Armstrong number.
Complexity
Time Complexity
O(log₁₀ n)
Space Complexity
O(1)