C Program for Armstrong Number of n Digits
The idea is to first count the number of digits (or find the order). Let the number of digits be n. For every digit r in input number x, compute rn. If the sum of all such values is equal to n, then return true, else false.
C
// C program to check given number // is Armstrong number or not // using Functions #include <stdio.h> // math.h is used for pow function. #include <math.h> // Function to calculate // order of the number int order( int x) { int n = 0; while (x) { n++; x = x / 10; } return n; } // Function to check whether the // given number is Armstrong // number or not int isArmstrong( int x) { // Calling order function int n = order(x); int temp = x, sum = 0; while (temp) { int r = temp % 10; sum += pow (r, n); temp = temp / 10; } // If satisfies Armstrong condition if (sum == x) return 1; else return 0; } // Driver Program int main() { int x = 153; if (isArmstrong(x) == 1) printf ( "True\n" ); else printf ( "False\n" ); x = 1253; if (isArmstrong(x) == 1) printf ( "True\n" ); else printf ( "False\n" ); return 0; } |
Output:
true false
- Time Complexity: O(logx*log(logx))
- Auxiliary Space: O(1)
C Program to Check Armstrong Number
In this article, we will see how to check Armstrong number in the c program. We can implement two logic for checking Armstrong numbers, one for 3-digit numbers and the second one for more than 3 digits.
Contact Us