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.
- Print numbers such that no two consecutive numbers are co-prime and every three consecutive numbers are co-prime
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array
- Count prime numbers that can be expressed as sum of consecutive prime numbers
- Permutation of first N positive integers such that prime numbers are at prime indices
- Permutation of first N positive integers such that prime numbers are at prime indices | Set 2
- Absolute difference between the Product of Non-Prime numbers and Prime numbers of an Array
- Absolute difference between the XOR of Non-Prime numbers and Prime numbers of an Array
- Prime numbers after prime P with sum S
- 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
- Sum of prime numbers without odd prime digits
- Count all prime numbers in a given range whose sum of digits is also prime
- Bitwise AND of the sum of prime numbers and the sum of composite numbers in an array
- Print the nearest prime number formed by adding prime numbers to N
- Print all numbers whose set of prime factors is a subset of the set of the prime factors of X
- Check if a number is Prime, Semi-Prime or Composite for very large numbers
- Number of distinct prime factors of first n natural numbers
- Find the Product of first N Prime Numbers
- Find prime numbers in the first half and second half of an array
- Find the XOR of first N Prime Numbers
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.