Armstrong number

A number is armstrong if the sum of cubes of individual digits of a number is equal to the number itself. For example 371 is an armstrong number as 3^3 + 7^3 + 1^3 = 371. Some other armstrong numbers are: 0, 1, 153, 370, 407.

Armstrong number C code

Below is the logic to detect if it is armstrong number. We extract each digit starting from LSB (right most). We divide the number by 10. Reminder is the digit in LSB and same time all the digits will be shifted to right. We calculate the cube of remainder and add to the sum. Now we repeat the same for the rest of the digits till we exhaust the digits. Now the sum contains the sum of all cube of digits. We compare this sum with the original number. A match means the number is armstrong number.

#include <stdio.h>

int is_armstrong (int num)
{
  int sum = 0, temp, remainder;
  temp = num;

  while( temp != 0 )
  {
    /* Get the digit */
    remainder = temp % 10;
    /* calculate cube and sum up */
    sum = sum + (remainder * remainder * remainder);
    /* Shift right by one digit */
    temp = temp / 10;
  }

  if ( num == sum ) {
    return 1; /* armstrong number */
  } else {
    return 0; /* not armstrong number */
  }
}
int main(int argc, char *argv[])
{
  int number;

  printf ("Enter an integer: ");
  scanf ("%d",&number);

  if ( is_armstrong(number) ) {
    printf ("%d is an armstrong number.\n", number);
  } else {
    printf ("%d is not an armstrong number.\n", number);
  }
  return 0;
}

Output

Enter an integer: 153
153 is an armstrong number.

Armstrong number series

int main(int argc, char *argv[])
{
  int range;
  printf ("Enter Max range: ");
  scanf ("%d", &range);
  printf ("Printing armstrong numbers from 0 - %d\n", range);
  for (number = 0; number <= range; number++) {
    if ( is_armstrong(number) ) {
      printf ("%d, ", number);
    }
  }
  return 0;
}

Output

Enter Max range: 15000
Printing armstrong numbers from 0 - 15000
0, 1, 153, 370, 371, 407,

About our authors: Team EQA

You have viewed 1 page out of 252. Your C learning is 0.00% complete. Login to check your learning progress.

#