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 higherlimit = 1000
Output:
1 2 3 4 5 6 7 8 9 153 370 371 407
Example:
C
// C Program to Display Armstrong // numbers between 1 to 1000 #include <math.h> #include <stdio.h> int power( int x, unsigned int y)
{ int res = 1; // Initialize result
while (y > 0) {
// If y is odd, multiply
// x with result
if (y & 1)
res = res * x;
// y must be even now
y = y >> 1; // y = y/2
x = x * x; // Change x to x^2
}
return res;
} int main()
{ printf ( "Armstrong Numbers between 1-1000 are:\n" );
for ( int i = 1; i < 1000; ++i) {
int x = i;
int n = 0;
// number of digits calculation
while (x != 0) {
x /= 10;
++n;
}
int powersum = 0;
x = i;
// finding the sum of nth
// power of its digits
while (x != 0) {
int digit = x % 10;
powersum += power(digit, n);
x /= 10;
}
// checking if the obtained
// number is armstrong or not
if (powersum == i)
// printing the result
printf ( "%d " , i);
}
printf ( "\n" );
return 0;
} |
Output
Armstrong Numbers between 1-1000 are: 1 2 3 4 5 6 7 8 9 153 370 371 407