Armstrong number in C

Armstrong number in C
Armstrong number in C

Problem Statement: Given a number N, check if the number is Armstrong’s number or not.

Examples:

Example 1:
Input: N = 153
Output: Armstrong Number
Explanation: 153 = 1^3 + 5^3 + 3^3

Example 2:
Input: N = 154
Output: Not Armstrong Number
Explanation: 154 ! = 1^3 + 5^3 + 4^3

DisclaimerDon’t jump directly to the solution, try it out yourself first.

What is Armstrong Number?

A number is thought of as an Armstrong number if the sum of its own digits raised to the power (number of digits) gives the number itself.

As you have already seen in the examples above, 153 is an armstrong number because,

  • Number of digits in 153 is 3.
  • And, sum of every digit raised to the power 3 is 153.

Approach:

  • First of all, calculate the total number of digits in the given number.
  • Once we have the number of digits, run a loop and extract every digit of the number starting from last digit to first digit.
    • To extract last digit, divide the number by 10 and the remainder will the required digit. We can simply use to modulo(%) operator to do this.
  • Simultaneously, calculate the sum of digits raised to the power (number of digits).
  • In the end, check if the sum is the same as original number or not.

Code:

C Program

#include<stdio.h>
#include<math.h>
int ArmstrongNumber(int n)
{
    int originalno = n;
    int count = 0;
    int temp = n;
    while (temp != 0)
    {
        count++;
        temp = temp / 10;
    }
    int sumofpower = 0;
    while (n != 0)
    {
        int digit = n % 10;
        sumofpower += pow(digit,count);
        n /= 10;
    }
    return (sumofpower == originalno);
}

int main()
{
    int n1 = 153;
    if (ArmstrongNumber(n1))
    {
        printf("Yes, it is an Armstrong Number\n");
    }
    else
    {
        printf("No, it is not an Armstrong Number\n");
    }
    return 0;
}

Output:

Yes, it is an Armstrong Number

Time Complexity: O(n) where n is the number of digits since we need to traverse every digit and add digits raised to power no. of digits to sum.

Space Complexity: O(1) since no extra space is required

Special thanks to Subhrajit Das for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article