Introduction
This blog will discuss the solution to this problem of checking if a number is an Armstrong number or not. We will code the solution to this problem in C language. We will discuss three different approaches to solve this problem. But before discussing the different solutions to this problem, we should first look at what exactly an Armstrong number is and by whom it was found.
A number is called an Armstrong number if the sum of every digit present in that number raised to the number of digits is equal to that number. Armstrong's number, also known as the narcissistic number, was discovered by Michael Armstrong and was also named after him.
Here is a general representation of an Armstrong number,
Sample Examples
Example 1:
Input:
N = 371
Output
371 is an Armstrong number.
Explanation
3*3*3 + 7*7*7 + 1*1*1 = 27 + 343 + 1 = 371
Since the sum of individual powers of every digit is equal to the number itself, therefore this number is an Armstrong number.
Example 2:
Input:
N = 8208
Output:
8208 is an Armstrong number
Explanation
8*8*8*8 + 2*2*2*2 + 0*0*0*0 + 8*8*8*8 = 4096 + 16 + 0 + 4096 = 8208
Since the sum of individual powers of every digit is equal to the number itself, therefore we can say that the given number is Armstrong's number.
You can also read about dynamic array in c and C Static Function.
Also Read - Strong number in c
Armstrong Number Using a For Loop
- First, we will calculate the number of digits in a number N using a while loop.
- After that, we run a for loop from 0 to the number of digits of the number, and at each iteration, we will take the current digit and add the current digit raised to the power of the number of digits in the sum variable.
- In the last, we will check if the sum value is equal to N. We will print that the given number N is an Armstrong number. Else we will print that the given number is not an Armstrong number.
Implementation in C++
// C program to check if a number is Armstrong Number or not
#include <stdio.h>
#include <math.h>
int main()
{
int N, countOfDigits=0, temp = 0;
scanf("%d", &N);
temp = N;
while (temp != 0) // to count the digits in the number
{
countOfDigits = countOfDigits + 1;
temp = temp / 10;
}
int r, sum = 0;
for (int i = N; i > 0; i = i / 10)
{
r = i % 10; // to store the digit
sum = sum + pow(r, countOfDigits); // to store the sum
}
if (N == sum)
printf("%d is an Armstrong Number.\n", N);
else
printf("%d is not an Armstrong Number.\n", N);
return 0;
}
Output:
Input: N = 1634
Output: 1634 is an Armstrong Number
1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1 + 1296 + 81 + 216 = 1634
Complexity Analysis
Time Complexity: O(log(N))
Since we are using a single for loop from 0 to the count of the digits, therefore, we can say that the complexity of the above approach is O(Count of digits of a Number) which is approximately equal to O(log(N)).
Space Complexity: O(1)