C Program to Check Armstrong Number
Last Updated :
14 Aug, 2024
Write a C program to check whether the given number is an Armstrong number or not. It should print “Yes” if the number is Armstrong number, otherwise, it should print “No”.
An Armstrong number can be defined as a number that is equal to the sum of the Kth power of each digit in the number, where K is the number of digits in it.
For example, a number XYZ, which is 3-digit number, is Armstrong number if: XYZ = X3 + Y3 + Z3
Example:
Input: 153
Output: Yes
Explanation: 153 is an Armstrong number of 3 digits, since the sum of cubes of each digit is equal to the number itself.
13 + 53 + 33= 153
Input: 12
Output: No
Explanation: 12 is not an Armstrong number as the sum of square of each digit is not equal to the number:
12+ 22 = 5 ≠ 12
Armstrong Number Program in C
We can determine whether the given number is an Armstrong number by first extracting each digit, raising them to the power of the total number of digits, and adding them. If the sum is equal to the original number, it’s an Armstrong number, otherwise, it’s not.
Below are the steps to check Armstrong number in a C program:
- Find the number of digits K in the given number N using log10() function.
- Create a temporary variable temp = N so that we don’t lose the original number.
- Create a loop that runs K number of times (you can also set temp > 0 as termination condition). In this loop,
- Extract the last digit using modulo operator: (temp % 10)
- Raise it to the power of the number of digits and add it to the sum of digits sum.
- Remove the last digit from the number using formula: temp = temp / 10
- Compare the sum with the original number N.
- Print “Yes” if they are equal, otherwise print “No“.
C Program to Check for Armstrong Number
C
// C program to check given number is Armstrong number
// or not using Functions
#include <math.h>
#include <stdio.h>
#include <stdbool.h>
bool isArmstrong(int N) {
int temp = N;
int sum = 0;
// Get the number of digits
// Adding 1 to compensate for the loss of fraction part
// of the value returned by log10 due to the conversion
// into integer
int K = log10(temp) + 1;
// Calculate the sum of the digits raised to the power of
// num_digits
while (temp > 0) {
int digit = temp % 10;
sum += pow(digit, K);
temp /= 10;
}
// Return whether the sum is equal to the original number or not
return (sum == N);
}
int main() {
int N = 153;
// Check if the number is an Armstrong number
if (isArmstrong(N)) {
printf("Yes\n");
}
else {
printf("No\n");
}
return 0;
}
Time Complexity: O(logN * log(logN)), where N is the given number.
Auxiliary Space: O(1)
Different Methods to Check for Armstrong Number in C
The above method is the most straightforward method to check for Armstrong number in C, but we can also use other methods. Following are some commonly used methods to check for Armstrong number in C:
1. Check For Armstrong Number Using Recursion
We can convert the iterative method discussed above into recursive method by considering only a single digit of the number in each recursive call and calling the function again for the number with remaining digits.
Below are the steps to implement a recursive function to check for Armstrong number in C:
- Create a recursive function armstrongSum(). In this function,
- Calculate the value of the last digit raised to the power of the total number of digits, K.
- Add it to the sum of the remaining digits raised to the power of K by making a recursive call. This call processes the next digit by removing the current last digit from the number.
- Continue this process until N becomes 0, indicating that all digits have been processed, at which point the function returns 0.
- Compare the sum returned by the armstrongSum() function with the original number.
- If the sum equals the original number, return true; otherwise, return false.
C Program to Check For Armstrong Number Using Recursion
C
// C Program to Check Armstrong Number Using Recursion
#include <math.h>
#include <stdio.h>
#include <stdboo.h>
// Recursive function to calculate the sum of digits raised
// to the power of num_digits
int armstrongSum(int N, int K)
{
if (N == 0) {
return 0;
}
int digit = N % 10;
return pow(digit, K) + armstrongSum(N / 10, K);
}
// Function to check if the number is an Armstrong number
bool isArmstrong(int N) {
// Finding the number of digits
int K = log10(N) + 1;
// Calculating the sum
int sum = armstrongSum(N, K);
// Returning whether the sum is equal to the original
// number or not
return (sum == N);
}
int main() {
int num = 153;
// Check if the number is an Armstrong number
if (isArmstrong(num)) {
printf("Yes\n");
}
else {
printf("No\n");
}
return 0;
}
Time Complexity: O(logN * log(logN)), where N is the given number.
Auxiliary Space: O(logN) due to recursion stack.
2. Check For Armstrong Number Using a Numeric Strings
In this method, we convert the number to the numeric string so each digit can be easily accessed. Then easily find the sum of digits raised to the power of number of digits by converting them back to integer and using arithmetic.
Below are the steps to implement the above approach:
- Convert the number N to the string using sprintf()
- Calculate the number of digits K from the length of the string.
- Create an integer variable sum = 0.
- Iterate through each character in the string and do this:
- Convert the character to an integer.
- Raise it to the power K and add it to the sum.
- Compare the sum with the original number.
- Return true if they are equal, false otherwise.
C Program to Check for Armstrong Number Using Recursion
C
// C Program to Check Armstrong Number Using Numeric Strings
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdboo.h>
int isArmstrong(int N) {
// Convert the number to a string
char n_str[20];
sprintf(n_str, "%d", N);
// Get the number of digits in the string
int K = strlen(n_str);
int sum = 0;
// Calculate the sum of the digits raised to the power
// of num_digits
for (int i = 0; i < K; i++)
{
int digit = n_str[i] - '0';
sum += pow(digit, K);
}
// Return whether the sum equals the original number
return sum == N;
}
int main()
{
int N = 153;
// Check if the number is an Armstrong number
if (isArmstrong(N)) {
printf("Yes\n");
}
else {
printf("No\n");
}
return 0;
}
Time Complexity: O(logN * log(logN)) where N is the number.
Auxiliary Space: O(logN) due to the space occupied by string.
Conclusion
Checking for an Armstrong number involves calculating the sum of each digit raised to the power of the number of digits in the given number and comparing this sum to the original number. This can be efficiently implemented using various methods such as the iterative method, recursion, and using numeric strings.
Frequently Asked Questions on C Armstrong Number – FAQs
Is there any other method to check Armstrong numbers?
The basic iterative method is the most straightforward approach. There might be minor variations in implementation, but the underlying logic remains the same.
What is the difference between the iterative and recursive methods?
The iterative method uses loops to process each digit, while the recursive method uses function calls. The recursive method can be more elegant but may have higher space complexity due to the call stack.
How does using numeric strings help?
Using numeric strings makes it easier to access each digit without repeatedly dividing and taking remainders. This approach is intuitive and leverages string operations to process the digits.
Related Articles:
Similar Reads
C Program to Check Armstrong Number
Write a C program to check whether the given number is an Armstrong number or not. It should print "Yes" if the number is Armstrong number, otherwise, it should print "No". An Armstrong number can be defined as a number that is equal to the sum of the Kth power of each digit in the number, where K i
7 min read
C/C++ program for Armstrong Numbers
Given a number N, the task is to check whether the given number is Armstrong number or not. If the given number is Armstrong Number then print "Yes" else print "No". A positive integer of D digits is called an armstrong-numbers of order D (order is the number of digits) if [Tex]N_{1}N_{2}N_{3}N_{4}.
3 min read
C Program To Find Armstrong Numbers Between 1 to 1000
Prerequisites: Program for Armstrong Numbers A positive integer of n digits is called Armstrong number of order n (order is the number of digits) if xyz⦠= pow(x,n) + pow(y,n) + pow(z,n) + â¦. Here we will build a C Program to print Armstrong numbers between 1 to 1000 Input: lowerlimit = 1 higherlimi
2 min read
C Program to Find Armstrong Numbers Between Two Integers
Prerequisite: Program for Armstrong Numbers A positive integer of n digits is called Armstrong number of order n (order is the number of digits) if abcd⦠= pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + â¦. Here, we will build a C Program to print Armstrong Numbers between two integers. Example: 153 is
3 min read
C Program to Print Armstrong Numbers Between 1 to 1000
Armstrong numbers are those numbers in which the sum of digits raised to the power of a number of digits in that number will be equal to the number itself. Here will see how to build a C Program to Display Armstrong numbers between 1 to 1000. Example: 153 13 + 53 + 33 1 + 125 + 27 = 153Approach 1:Co
3 min read
C Program to Display Armstrong Number Between Two Intervals
Write a C program to find and display all Armstrong numbers between two given intervals. An Armstrong number (also known as a narcissistic number or pluperfect number) of a given number of digits is a number that is equal to the sum of its own digits each raised to the power of the number of digits.
6 min read
C Program to check whether a number is a Perfect Cube or not
Given a number N, the task is to write C program to check if the given number is perfect cube or not. Examples: Input: N = 216Output: YesExplanation:As 216 = 6*6*6.Therefore the cube root of 216 is 6. Input: N = 100Output: No Method 1: Naive Approach To find the cube root of the given number iterate
5 min read
C Program to Check for Majority Element in a sorted array
Question: Write a function to find if a given integer x appears more than n/2 times in a sorted array of n integers. Basically, we need to write a function say isMajority() that takes an array (arr[] ), arrayâs size (n) and a number to be searched (x) as parameters and returns true if x is a majorit
7 min read
C Program To Check If A Singly Linked List Is Palindrome
Given a singly linked list of characters, write a function that returns true if the given list is a palindrome, else false. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. METHOD 1 (By reversing the list): This method takes O(n) time and O(1) extra space. 1) Get t
7 min read
C Program to Detect Cycle in a Directed Graph
Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false. For example, the following graph contains three cycles 0->2->0, 0->1->2->0 and 3->3, so your function must return true. Recomme
3 min read