Print the Average of All Prime Numbers Between 1 to n in C
In this tutorial, we will write a C program to calculate and print the average of all prime numbers between 1 and n.
What is a Prime Number?
A prime number is a number greater than 1 that has exactly two positive divisors: 1 and itself.
Examples: 2, 3, 5, 7, 11, 13, etc.
Algorithm
- Input the value of n.
- Loop from 2 to n.
- For each number, check whether it is prime.
- If prime, add it to sum and increase count.
- After the loop, calculate average = sum / count.
C Program
#include <stdio.h>
int main() {
int n, i, j, isPrime;
int sum = 0, count = 0;
float average;
printf("Enter the value of n: ");
scanf("%d", &n);
for(i = 2; i <= n; i++) {
isPrime = 1;
for(j = 2; j * j <= i; j++) {
if(i % j == 0) {
isPrime = 0;
break;
}
}
if(isPrime) {
sum += i;
count++;
}
}
if(count == 0) {
printf("No prime numbers found.\n");
} else {
average = (float)sum / count;
printf("Average of prime numbers between 1 and %d is: %.2f\n", n, average);
}
return 0;
}
Explanation
1. Prime Checking Logic
for(j = 2; j * j <= i; j++)
We check divisibility only up to the square root of the number for efficiency. If any divisor is found, the number is not prime.
2. Sum and Count
If a number is prime:
sum += i;
count++;
3. Average Calculation
average = (float)sum / count;
We cast sum to float to get a decimal result.
Sample Input
Enter the value of n: 10
Output
Average of prime numbers between 1 and 10 is: 4.25
(Prime numbers between 1 and 10 are 2, 3, 5, 7 → Average = 17 / 4 = 4.25)
Time Complexity
The outer loop runs n times, and prime checking runs up to √n. Therefore, the overall time complexity is approximately O(n√n).
কোন মন্তব্য নেই:
একটি মন্তব্য পোস্ট করুন