VOOZH about

URL: https://www.geeksforgeeks.org/dsa/largest-subset-with-sum-of-every-pair-as-prime/

⇱ Largest subset with sum of every pair as prime - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Largest subset with sum of every pair as prime

Last Updated : 28 Jul, 2022

Given an array A[], find a subset of maximum size in which sum of every pair of elements is a prime number. Print its length and the subset. Consider many queries for different arrays and maximum value of an element as 100000.

Examples : 

Input : A[] = {2, 1, 2}
Output : 2
 1 2
Explanation :
Here, we can only form subsets with size 1 and 2.
maximum sized subset = {1, 2}, 1 + 2 = 3, which 
is prime number.
So, Answer = 2 (size), {1, 2} (subset)

Input : A[] = {2, 1, 1}
Output : 3
 1 1 2
Explanation :
Maximum subset = {2, 1, 2}, since 1 + 2 = 3,
1 + 1 = 2, both are prime numbers.
Answer = 3 (size), {2, 1, 1} (subset).

Let's make some observations and then move to problem. Sum of two numbers is even if and only both the numbers are either odd or even. An even number cannot be a prime number except 2. Now, if we take three numbers a, b and c, two of them should be either odd or even(Pigeonhole theorem). So, our solution exists only in two cases - (Let the subset be B)

  • Case I : When B contains only two integers(>1) whose sum is a prime number.
  • Case II : When B contains some number of ones(1s) and another number X, where X + 1 should be a prime(Only possible when X is an even number).

First count the number of ones in the array using a for loop. 

  1. If the count of 1s is greater than 0, then traverse the whole the array and check if [A[i] + 1] is a prime number and (A[i] != 1), if found any, print the size of subarray as (count of 1s) +1 and all the ones(1s) and the found A[i]. Exit the program.
  2. If the above step fails (i.e, A[i] not found), print all the ones(1s). Exit the program.
  3. If above step fails (i.e, count of 1s = 0), Check every pair of elements in the array for their sum to be a prime. Print 2 and the pair of integers.
  4. Else Print -1.

Below is implementation of above approach : 

Output:  

3
1 1 2

Time Complexity : O(n2)

Comment