C Program to Find Armstrong Numbers Between Two Integers
Prerequisite: Program for Armstrong Numbers
A positive integer of n digits is called Armstrong number of order n (order is the number of digits) if
abcd… = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + ….
Here, we will build a C Program to print Armstrong Numbers between two integers.
Example:
153 is an Armstrong number 1*1*1 + 5*5*5 + 3*3*3 = 153 370 is an Armstrong Number 3*3*3 + 7*7*7 + 0*0*0 = 370
Input:
lowerlimit = 100 higherlimit = 400
Output:
153 370 371
Below is the program to print all Armstrong numbers between the lower limit and the upper limit provided by the user.
C
// C Program to Demonstrate // Armstrong numbers between // two integers #include <math.h> #include <stdio.h> int power( int x, unsigned int y) { // Initialize result int res = 1; 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() { int lowerlimit, higherlimit; printf ( "Enter lowerlimit and Higher limit:\n " ); scanf ( "%d%d" , &lowerlimit, &higherlimit); for ( int i = lowerlimit + 1; i < higherlimit; ++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 n // th 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:
Enter lowerlimit and Higher limit: 100 400 153 370 371
Time Complexity: The time complexity of the program is O((n-m) * d * log(p)) where n and m are the given lower and upper limits respectively, d is the number of digits in the largest number in the range and p is the number of digits in the base of the number system (10 in this case).
Space Complexity: The space complexity of the program is O(1) as it uses only a constant amount of extra space regardless of the input size.
Contact Us