In this C programming tutorial, we are going to learn how to check if the given number is an Armstrong number or not. But before moving to the code section let us first understand what is an Armstrong number?
Armstrong Numbers.
An Armstrong number is a number that is equal to the sum of its own digits, each raised to the power of the number of digits in the number. Let's try to understand this with an example.
Example:
Input: 371 Output: Armstrong Number. Explanation: Total number of digits = 3 = 3^3 + 7^3 + 1^3 = 3*3*3 + 7*7*7 + 1*1*1 = 27 + 343 + 1 = 371
C Program to check Three Digits, Armstrong Numbers.
//C code to check three digit armstrong number #include <stdio.h> #include <math.h> int main() { int num, originalNum, remainder, result = 0; printf("Enter a three-digit number: "); scanf("%d", &num); if (num < 100 || num > 999) { printf("Invalid input.\n"); return 0; } originalNum = num; while (originalNum != 0) { remainder = originalNum % 10; result += pow(remainder, 3); originalNum /= 10; } if (result == num) { printf("%d is an Armstrong number.\n", num); } else { printf("%d is not an Armstrong number.\n", num); } return 0; }
Enter a three-digit number: 153
153 is an Armstrong number.
C Program to check n digits Armstrong Number.
//C code to check armstrong number of n digits #include <stdio.h> #include <math.h> int main() { int num, originalNum, remainder, result = 0, n = 0; printf("Enter an integer: "); scanf("%d", &num); originalNum = num; // Count the number of digits while (originalNum != 0) { originalNum /= 10; ++n; } originalNum = num; // Calculate the result while (originalNum != 0) { remainder = originalNum % 10; result += pow(remainder, n); originalNum /= 10; } // Check if the number is Armstrong if (result == num) { printf("%d is an Armstrong number.\n", num); } else { printf("%d is not an Armstrong number.\n", num); } return 0; }
Enter an integer: 1634 1634 is an Armstrong number.
Time Complexity: The time complexity of the above C program to check if a number is an Armstrong number is O(d), where 'd' is the number of digits in the input number.
Space Complexity: The space complexity of the program is O(1), which means it uses constant space.
No comments:
Post a Comment