Given an integer ‘n’, the task is to find the sum of first ‘n’ prime numbers.
First few prime numbers are: 2, 3, 5, 7, 11, 13, 17, 19, 23, ……
Input: N = 4 Output: 17 2, 3, 5, 7 are first 4 prime numbers so their sum is equal to 17 Input: N = 40 Output: 3087
- Create a sieve which will help us to identify if the number is prime or not in O(1) time.
- Run a loop starting from 1 until and unless we find n prime numbers.
- Add all the prime numbers and neglect those which are not prime.
- Then, display the sum of 1st N prime numbers.
Below is the implementation of the above solution
Sum of 1st N prime numbers are :17
Note(For competitive programming): In a problem which contains a large number of queries, a vector can be used to store all the prime numbers in the range of 10^8, this will take extra O(N) space. We can also use prefix array to store the sum of first N prime numbers in the range of 10^8.
- Absolute difference between the Product of Non-Prime numbers and Prime numbers of an Array
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array
- Print the nearest prime number formed by adding prime numbers to N
- Check if a prime number can be expressed as sum of two Prime Numbers
- Print prime numbers with prime sum of digits in an array
- Print numbers such that no two consecutive numbers are co-prime and every three consecutive numbers are co-prime
- Numbers less than N which are product of exactly two distinct prime numbers
- Print all numbers whose set of prime factors is a subset of the set of the prime factors of X
- Prime numbers after prime P with sum S
- Prime Numbers
- Almost Prime Numbers
- XOR of all Prime numbers in an Array
- Twin Prime Numbers
- Special prime numbers
- Prime numbers in a given range using STL | Set 2
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.