C Example Code2026-03-202 min read
Learn how to check if a number is an Armstrong (narcissistic) number in C for any number of digits with full working code and complexity analysis.
What is an Armstrong Number?
An Armstrong number (also called a narcissistic number or pluperfect digital invariant) is an integer such that the sum of its digits raised to the power of the total number of digits equals the original number.
Examples:
- 153 (3 digits): $1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153$ (Armstrong)
- 371 (3 digits): $3^3 + 7^3 + 1^3 = 27 + 343 + 1 = 371$ (Armstrong)
- 1634 (4 digits): $1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634$ (Armstrong)
C Implementation for Any Number of Digits
c (ISO Standard)#include <stdio.h> #include <math.h> #include <stdbool.h> int countDigits(int n) { int count = 0; while (n > 0) { count++; n /= 10; } return count; } bool isArmstrong(int n) { if (n < 0) return false; int original = n; int digits = countDigits(n); int sum = 0; int temp = n; while (temp > 0) { int remainder = temp % 10; sum += (int)round(pow(remainder, digits)); temp /= 10; } return sum == original; } int main() { int testCases[] = {153, 370, 371, 407, 1634, 123}; int size = sizeof(testCases) / sizeof(testCases[0]); printf("Verifying Armstrong Numbers in C:\n"); for (int i = 0; i < size; i++) { int num = testCases[i]; if (isArmstrong(num)) { printf(" -> %d is an Armstrong number.\n", num); } else { printf(" -> %d is NOT an Armstrong number.\n", num); } } return 0; }
Sample Output
text (ISO Standard)Verifying Armstrong Numbers in C: -> 153 is an Armstrong number. -> 370 is an Armstrong number. -> 371 is an Armstrong number. -> 407 is an Armstrong number. -> 1634 is an Armstrong number. -> 123 is NOT an Armstrong number.
Complexity Analysis
- Time Complexity:
O(log₁₀ n)— We iterate over the digits twice: once to count the digits and once to accumulate the powers. - Auxiliary Space:
O(1)— Only a few primitive integer variables are stored.
Related Programs & Guides
- Compare digit manipulation in Palindrome Program in C.
- Review mathematical operators in C Operators Reference.
- Try running this code in the Online C Compiler.