Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Sum of the first N Prime numbers
In C programming, finding the sum of the first N prime numbers involves identifying prime numbers sequentially and adding them together. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Syntax
int isPrime(int num); int sumOfFirstNPrimes(int n);
Algorithm
The approach involves checking each number starting from 2 for primality, and when a prime is found, adding it to the sum until we have found N primes −
- Start with the first prime number (2)
- Check each subsequent number for primality
- Add prime numbers to the running sum
- Stop when N primes have been found
Example
Here's a complete program to find the sum of the first N prime numbers −
#include <stdio.h>
int isPrime(int num) {
if (num <= 1) {
return 0;
}
if (num == 2) {
return 1;
}
if (num % 2 == 0) {
return 0;
}
for (int i = 3; i * i <= num; i += 2) {
if (num % i == 0) {
return 0;
}
}
return 1;
}
int main() {
int n = 5;
int count = 0;
int sum = 0;
int num = 2;
printf("First %d prime numbers: ", n);
while (count < n) {
if (isPrime(num)) {
printf("%d ", num);
sum += num;
count++;
}
num++;
}
printf("\nSum of first %d prime numbers: %d<br>", n, sum);
return 0;
}
First 5 prime numbers: 2 3 5 7 11 Sum of first 5 prime numbers: 28
How It Works
The isPrime() function efficiently checks primality by −
- Handling special cases (numbers ? 1, number 2, even numbers)
- Checking odd divisors only up to ?num for optimization
- Returning 1 for prime, 0 for non-prime
The main function iterates through numbers starting from 2, checks each for primality, and maintains a running sum until N primes are found.
Time Complexity
The time complexity is O(N × ?M) where N is the count of primes needed and M is the largest number checked. The space complexity is O(1) as only a constant amount of extra space is used.
Conclusion
This approach efficiently finds the sum of the first N prime numbers using an optimized primality test. The algorithm works by sequentially checking numbers and accumulating the sum of identified primes.
