CodersZone logo

Armstrong Number

An Armstrong number is a positive m-digit number that is equal to the sum of the m th powers of their digits. It is also known as pluperfect, or Plus Perfect, or Narcissistic number.
We need two parameters to implement armstrong numbers. One is the number of digits in the number, and second the sum of the digits raised to the power of a number of digits.
Let’s understand it through an example:

1: 11 = 1
2: 21 = 2
3: 31 = 3
153: 13 + 53 + 33 = 1 + 125+ 27 = 153
125: 13 + 23 + 53 = 1 + 8 + 125 = 134 (Not an Armstrong Number)
1634: 14 + 64 + 34 + 44 = 1 + 1296 + 81 + 256 = 1643

Similarly, we can check other number also.
The first few Armstrong numbers between 0 to 999 are 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407. Some other Armstrong numbers are 1634, 8208, 9474, 54748, 92727, 93084, 548834, 1741725, 4210818, 9800817, 9926315, 24678050, 24678051, 88593477, 146511208, 472335975, 534494836, 912985153, 4679307774, 32164049650, 32164049651.

Algorithm

  1. The number of digits in num is found out
  2. The individual digits are obtained by performing num mod 10, where the mod is the remainder operation.
  3. The digit is raised to the power of the number of digits and stored
  4. Then the number is divided by 10 to obtain the second digit.
  5. Steps 2, 3 and 4 are repeated until the value of num is greater than 0
  6. Once num is less than 0, end the while loop
  7. Check if the sum obtained is same as the original number
  8. If yes, then the number is an armstrong number

Code

    #include  < stdio.h >
            
    int main() {
        int num, originalNum, remainder, result = 0;
        printf("Enter a three-digit integer: ");
        scanf("%d", &num);
        originalNum = num;
                    
        while (originalNum != 0) {
                           
            // remainder contains the last digit
            remainder = originalNum % 10;
                            
            result += remainder * remainder * remainder;
                            
            // removing last digit from the original number
            originalNum /= 10;
        }
                    
        if (result == num)
            printf("%d is an Armstrong number.", num);
        else
            printf("%d is not an Armstrong number.", num);
                    
        return 0;
    }
                    
           

Output

Enter a three-digit integer: 371
371 is an Armstrong number.
                
 
See the same program in Java See the same program in python