VOOZH about

URL: https://www.geeksforgeeks.org/dsa/pair-of-prime-numbers-with-a-given-sum-and-minimum-absolute-difference/

⇱ Pair of prime numbers with a given sum and minimum absolute difference - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Pair of prime numbers with a given sum and minimum absolute difference

Last Updated : 25 Aug, 2022

Given an integer 'sum' (less than 10^8), the task is to find a pair of prime numbers whose sum is equal to the given 'sum' 
Out of all the possible pairs, the absolute difference between the chosen pair must be minimum. 
If the ‘sum’ cannot be represented as a sum of two prime numbers then print “Cannot be represented as sum of two primes”.
Examples: 
 

Input : Sum = 1002
Output : Primes: 499 503
Explanation
1002 can be represented as sum of many prime number pairs
such as
499 503
479 523
461 541
439 563
433 569
431 571
409 593
401 601...
But 499 and 503 is the only pair which has minimum difference 

Input :Sum = 2002
Output : Primes: 983 1019


 


Solution 
 

  • We will create a sieve of Eratosthenes which will store all the prime numbers and check whether a number is prime or not in O(1) time.
  • Now, to find two prime numbers with sum equal to the given variable, 'sum'. We will start a loop from sum/2 to 1 (to minimize the absolute difference) and check whether the loop counter 'i' and 'sum-i' are both prime.
  • If they are prime then we will print them and break out of the loop.
  • If the 'sum' cannot be represented as a sum of two prime numbers then we will print "Cannot be represented as sum of two primes".


Below is the implementation of the above solution: 
 


Output: 
499 503

 

Time Complexity: O(n + MAX3/2)

Auxiliary Space: O(MAX)

Comment