Find All Armstrong Numbers Between 1 to n in C
In this tutorial, we will write a C program to find and print all Armstrong numbers between 1 and n.
What is an Armstrong Number?
An Armstrong number (also called a narcissistic number) is a number that is equal to the sum of its digits each raised to the power of the number of digits.
Example:
153 = 1³ + 5³ + 3³
= 1 + 125 + 27
= 153
So, 153 is an Armstrong number.
Algorithm
- Input the value of n.
- For each number from 1 to n:
- Count the number of digits.
- Calculate the sum of each digit raised to the power of total digits.
- If sum equals the number, print it.
C Program
#include <stdio.h>
#include <math.h>
int main() {
int n, i, num, digit, count;
int sum;
printf("Enter the value of n: ");
scanf("%d", &n);
printf("Armstrong numbers between 1 and %d are:\n", n);
for(i = 1; i <= n; i++) {
num = i;
count = 0;
sum = 0;
// Count digits
int temp = num;
while(temp != 0) {
count++;
temp /= 10;
}
// Calculate sum of digits raised to power
temp = num;
while(temp != 0) {
digit = temp % 10;
sum += pow(digit, count);
temp /= 10;
}
// Check Armstrong condition
if(sum == num) {
printf("%d ", num);
}
}
return 0;
}
Explanation
Step 1: Input
The program takes an integer n from the user.
Step 2: Loop from 1 to n
Each number is checked individually.
Step 3: Count Digits
We count how many digits the number contains.
Step 4: Calculate Power Sum
Each digit is raised to the power of total digits using pow().
Step 5: Compare
If the calculated sum equals the original number, it is an Armstrong number.
Sample Input
Enter the value of n: 500
Output
Armstrong numbers between 1 and 500 are: 1 2 3 4 5 6 7 8 9 153 370 371 407
Time Complexity
For each number from 1 to n, we process its digits. So, the overall time complexity is approximately O(n × d), where d is the number of digits.
কোন মন্তব্য নেই:
একটি মন্তব্য পোস্ট করুন