Given three numbers sum S, prime P and N, find all N prime numbers after prime P such that their sum is equal to S.
Input : N = 2, P = 7, S = 28 Output : 11 17 Explanation : 11 and 17 are primes after prime 7 and (11 + 17 = 28) Input : N = 3, P = 2, S = 23 Output : 3 7 13 5 7 11 Explanation : 3, 5, 7, 11 and 13 are primes after prime 2. And (3 + 7 + 13 = 5 + 7 + 11 = 23) Input : N = 4, P = 3, S = 54 Output : 5 7 11 31 5 7 13 29 5 7 19 23 5 13 17 19 7 11 13 23 7 11 17 19 Explanation : All are prime numbers and their sum is 54
Approach : The approach used is to produce all the primes less than S and greater than P. And then backtracking to find if such N primes exist whose sum equals S.
For example, S = 10, N = 2, P = 2
7 47 11 43 13 41 17 37 23 31
The above solution can be optimized by pre-computing all required primes using Sieve of Eratosthenes
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Print numbers such that no two consecutive numbers are co-prime and every three consecutive numbers are co-prime
- Count prime numbers that can be expressed as sum of consecutive prime numbers
- Bitwise AND of the sum of prime numbers and the sum of composite numbers in an array
- 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
- 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
- Find all numbers between range L to R such that sum of digit and sum of square of digit is prime
- 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
- 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
- Check whether the sum of prime elements of the array is prime or not
- Numbers less than N which are product of exactly two distinct prime numbers
- Count of numbers upto M divisible by given Prime Numbers
- Longest Prime Subarray after removing one element
- Largest number not greater than N which can become prime after rearranging its digits
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.