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”.
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
- 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:
- Absolute difference between the Product of Non-Prime numbers and Prime numbers of an Array
- Pair with minimum absolute difference after solving each query
- Absolute Difference between the Sum 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
- Minimum absolute difference of a number and its closest prime
- Co-prime pair with given sum minimum difference
- Check whether the sum of absolute difference of adjacent digits is Prime or not
- Minimum absolute difference between N and any power of 2
- Minimum absolute difference between N and a power of 2
- Print all n-digit numbers with absolute difference between sum of even and odd digits is 1
- Find Maximum and Minimum of two numbers using Absolute function
- Predict the winner of the game on the basis of absolute difference of sum by selecting numbers
- Missing occurrences of a number in an array such that maximum absolute difference of adjacent elements is minimum
- Generate permutation of 1 to N such that absolute difference of consecutive numbers give K distinct integers
- Count all the numbers less than 10^6 whose minimum prime factor is N
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.