Given an array arr[] consisting of positive integers, the task is to check whether we can modify the array by adding any of the elements of the array such that it consists of only Primes.
Examples:
Input: arr[] = {3, 5, 7, 21}
Output: YES
Explanation:
Add the following elements, 3+5+21
So the array becomes {7, 29} which consists of only primes.Input: {2, 5, 12, 16}
Output: NO
Explanation:
There is no possible combination among elements which will make the array containing all primesInput: {3, 5, 13, 22}
Output: YES
Explanation:
Only one combination is possible,
Add all elements – 3+5+13+22 = {43} which is only prime
Pre-requisites: Bitmasking-DP
Approach:
- We can solve this problem using Dynamic Programming with Bitmasks. We can represent our DP state as a mask which is subset of elements.
- So let our dp array be DP[mask] which represents whether upto this mask (the chosen elements) the subset formed will elements are primes only.
- The max number of bits in mask will be the number of elements in the array.
- We keep on marking the elements encoded as a sequence in mask (If i-th index element is selected, then i-th bit is set in the mask) and keep checking whether the current chosen element (current sum) is prime, if it is prime and all other elements are visited, then we return true, and we get the answer.
- Else if other elements are not visited, then as the current sum is prime, we just need to search for other elements which can individually or by summing up to form some primes, so we can safely mark our current sum as 0 again.
- If the mask is full (All elements are visited) and the current sum is not prime, we return false, because there is atleast one sum that is not prime.
- Recurrence:
DP[mask] = solve(curr + arr[i], mask | 1<<i) where 0 <= i < n
Below is the implementation of the above approach.
C++
// C++ program to find the // array of primes #include <bits/stdc++.h> using namespace std; // DP array to store the // ans for max 20 elements bool dp[1 << 20]; // To check whether the // number is prime or not bool isprime(int n) { if (n == 1) return false; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { return false; } } return true; } // Function to check whether the // array can be modify so that // there are only primes int solve(int arr[], int curr, int mask, int n) { // If curr is prime and all // elements are visited, // return true if (isprime(curr)) { if (mask == (1 << n) - 1) { return true; } // If all elements are not // visited, set curr=0, to // search for new prime sum curr = 0; } // If all elements are visited if (mask == (1 << n) - 1) { // If the current sum is // not prime return false if (!isprime(curr)) { return false; } } // If this state is already // calculated, return the // answer directly if (dp[mask]) return dp[mask]; // Try all state of mask for (int i = 0; i < n; i++) { // If ith index is not set if (!(mask & 1 << i)) { // Add the current element // and set ith index and recur if (solve(arr, curr + arr[i] , mask | 1 << i, n)) { // If subset can be formed // then return true return true; } } } // After every possibility of mask, // if the subset is not formed, // return false by memoizing. return dp[mask] = false; } // Driver code int main() { int arr[] = { 3, 6, 7, 13 }; int n = sizeof(arr) / sizeof(arr[0]); if(solve(arr, 0, 0, n)) { cout << "YES"; } else { cout << "NO"; } return 0; } |
Java
// Java program to find the array of primes import java.util.*; class GFG{ // dp array to store the // ans for max 20 elements static boolean []dp = new boolean[1 << 20]; // To check whether the // number is prime or not static boolean isprime(int n) { if (n == 1) return false; for(int i = 2; i * i <= n; i++) { if (n % i == 0) { return false; } } return true; } // Function to check whether the // array can be modify so that // there are only primes static boolean solve(int arr[], int curr, int mask, int n) { // If curr is prime and all // elements are visited, // return true if (isprime(curr)) { if (mask == (1 << n) - 1) { return true; } // If all elements are not // visited, set curr=0, to // search for new prime sum curr = 0; } // If all elements are visited if (mask == (1 << n) - 1) { // If the current sum is // not prime return false if (!isprime(curr)) { return false; } } // If this state is already // calculated, return the // answer directly if (dp[mask]) return dp[mask]; // Try all state of mask for(int i = 0; i < n; i++) { // If ith index is not set if ((mask & (1 << i)) == 0) { // Add the current element // and set ith index and recur if (solve(arr, curr + arr[i], mask | 1 << i, n)) { // If subset can be formed // then return true return true; } } } // After every possibility of mask, // if the subset is not formed, // return false by memoizing. return dp[mask] = false; } // Driver code public static void main(String[] args) { int arr[] = { 3, 6, 7, 13 }; int n = arr.length; if(solve(arr, 0, 0, n)) { System.out.print("YES"); } else { System.out.print("NO"); } } } // This code is contributed by Rohit_ranjan |
Python3
# Python3 program to find the array # of primes # DP array to store the # ans for max 20 elements dp = [0] * (1 << 20) # To check whether the # number is prime or not def isprime(n): if (n == 1): return False for i in range(2, n + 1): if (n % i == 0): return False return True # Function to check whether the # array can be modify so that # there are only primes def solve(arr, curr, mask, n): # If curr is prime and all # elements are visited, # return true if (isprime(curr)): if (mask == (1 << n) - 1): return True # If all elements are not # visited, set curr=0, to # search for new prime sum curr = 0 # If all elements are visited if (mask == (1 << n) - 1): # If the current sum is # not prime return false if (isprime(curr) == False): return False # If this state is already # calculated, return the # answer directly if (dp[mask] != False): return dp[mask] # Try all state of mask for i in range(n): # If ith index is not set if ((mask & 1 << i) == False): # Add the current element # and set ith index and recur if (solve(arr, curr + arr[i], mask | 1 << i, n)): # If subset can be formed # then return true return True # After every possibility of mask, # if the subset is not formed, # return false by memoizing. return (dp[mask] == False) # Driver code arr = [ 3, 6, 7, 13 ] n = len(arr) if (solve(arr, 0, 0, n)): print("YES") else: print("NO") # This code is contributed by code_hunt |
C#
// C# program to find the array of primes using System; class GFG{ // dp array to store the // ans for max 20 elements static bool []dp = new bool[1 << 20]; // To check whether the // number is prime or not static bool isprime(int n) { if (n == 1) return false; for(int i = 2; i * i <= n; i++) { if (n % i == 0) { return false; } } return true; } // Function to check whether the // array can be modify so that // there are only primes static bool solve(int []arr, int curr, int mask, int n) { // If curr is prime and all // elements are visited, // return true if (isprime(curr)) { if (mask == (1 << n) - 1) { return true; } // If all elements are not // visited, set curr=0, to // search for new prime sum curr = 0; } // If all elements are visited if (mask == (1 << n) - 1) { // If the current sum is // not prime return false if (!isprime(curr)) { return false; } } // If this state is already // calculated, return the // answer directly if (dp[mask]) return dp[mask]; // Try all state of mask for(int i = 0; i < n; i++) { // If ith index is not set if ((mask & (1 << i)) == 0) { // Add the current element // and set ith index and recur if (solve(arr, curr + arr[i], mask | 1 << i, n)) { // If subset can be formed // then return true return true; } } } // After every possibility of mask, // if the subset is not formed, // return false by memoizing. return dp[mask] = false; } // Driver code public static void Main(String[] args) { int []arr = { 3, 6, 7, 13 }; int n = arr.Length; if(solve(arr, 0, 0, n)) { Console.Write("YES"); } else { Console.Write("NO"); } } } // This code is contributed by Rohit_ranjan |
YES
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.
Recommended Posts:
- Length of largest sub-array having primes strictly greater than non-primes
- Smallest integer greater than n such that it consists of digit m exactly k times
- Minimum operations required to modify the array such that parity of adjacent elements is different
- Count primes that can be expressed as sum of two consecutive primes and 1
- Count of primes below N which can be expressed as the sum of two primes
- Nth Term of a Fibonacci Series of Primes formed by concatenating pairs of Primes in a given range
- Maximum value after merging all elements in the array
- Minimum cost of reducing Array by merging any adjacent elements repetitively
- Count Numbers with N digits which consists of odd number of 0's
- Count Numbers with N digits which consists of even number of 0’s
- Smallest multiple of 3 which consists of three given non-zero digits
- Count of subsequences which consists exactly K prime numbers
- Check if a Binary Tree consists of a pair of leaf nodes with sum K
- Modify a binary array to Bitwise AND of all elements as 1
- Maximize occurrences of values between L and R on sequential addition of Array elements with modulo H
- Add N digits to A such that it is divisible by B after each addition
- Check whether an Array can be made 0 by splitting and merging repeatedly
- Maximum count of common divisors of A and B such that all are co-primes to one another
- Find the number of ordered pairs such that a * p + b * q = N, where p and q are primes
- Minimum number of primes required such that their sum is equal to 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 contribute@geeksforgeeks.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.

