C Program to Find Armstrong Numbers Between Two Integers
Last Updated :
23 Apr, 2023
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
#include <math.h>
#include <stdio.h>
int power( int x, unsigned int y)
{
int res = 1;
while (y > 0) {
if (y & 1)
res = res * x;
y = y >> 1;
x = x * x;
}
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;
while (x != 0) {
x /= 10;
++n;
}
int powersum = 0;
x = i;
while (x != 0) {
int digit = x % 10;
powersum += power(digit, n);
x /= 10;
}
if (powersum == i)
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.
Share your thoughts in the comments
Please Login to comment...