![]() |
VOOZH | about |
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)
First count the number of ones in the array using a for loop.
Below is implementation of above approach :
Output:
3 1 1 2
Time Complexity : O(n2)