Modify array by merging elements with addition such that it consists of only Primes . | C ++ program to find the array of primes ; DP array to store the ans for max 20 elements ; To check whether the number is prime or not ; Function to check whether the array can be modify so that there are only primes ; If curr is prime and all elements are visited , return true ; If all elements are not visited , set curr = 0 , to search for new prime sum ; If all elements are visited ; If the current sum is not prime return false ; If this state is already calculated , return the answer directly ; Try all state of mask ; If ith index is not set ; Add the current element and set ith index and recur ; If subset can be formed then return true ; After every possibility of mask , if the subset is not formed , return false by memoizing . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool dp [ 1 << 20 ] ; 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 ; } int solve ( int arr [ ] , int curr , int mask , int n ) { if ( isprime ( curr ) ) { if ( mask == ( 1 << n ) - 1 ) { return true ; } curr = 0 ; } if ( mask == ( 1 << n ) - 1 ) { if ( ! isprime ( curr ) ) { return false ; } } if ( dp [ mask ] ) return dp [ mask ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! ( mask & 1 << i ) ) { if ( solve ( arr , curr + arr [ i ] , mask 1 << i , n ) ) { return true ; } } } return dp [ mask ] = false ; } 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 ; }