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 )
  {
10      /* Get the digit */
11      remainder = temp % 10;
12      /* calculate cube and sum up */
13      sum = sum + (remainder * remainder * remainder);
14      /* Shift right by one digit */
15      temp = temp / 10;
16    }
17 
18    if ( num == sum ) {
19      return 1; /* armstrong number */
20    } else {
21      return 0; /* not armstrong number */
22    }
23  }
24  int main(int argc, char *argv[])
25  {
26    int number;
27 
28    printf ("Enter an integer: ");
29    scanf ("%d",&number);
30 
31    if ( is_armstrong(number) ) {
32      printf ("%d is an armstrong number.\n", number);
33    } else {
34      printf ("%d is not an armstrong number.\n", number);
35    }
36    return 0;
37  }

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);
10      }
11    }
12    return 0;
13  }

Output

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

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

 Vote 0

Similar topics related to this section

default C++ argument value, Recursion, factorial using recursion, Fibonaci using recursion, Armstrong number, variadic functions, variadic macro, multiple arguments in printf and scanf,

# C Programming Language (Prentice Hall Software)
# Let Us C Paperback - 2006 by Yashavant Kanetkar
# Understanding and Using C Pointers Core techniques for memory management
# Data Structures Using C and C++ Paperback - 1998
# Data Structures In C Paperback - August 11, 2008 by Noel Kalicharan