📌  相关文章
📜  通过合并元素和加法来修改数组,使其仅包含素数。

📅  最后修改于: 2021-09-07 02:25:21             🧑  作者: Mango

给定一个由正整数组成的数组arr[] ,任务是检查我们是否可以通过添加数组的任何元素来修改数组,使其仅包含素数。

例子:

先决条件:位掩码-DP
方法:

  • 我们可以使用带有位掩码的动态编程来解决这个问题。我们可以将我们的DP状态表示为一个掩码,它是元素的子集。
  • 因此,让我们的 dp 数组为DP[mask] ,它表示在此掩码(所选元素)之前,所形成的子集元素是否仅为素数。
  • 掩码中的最大位数将是数组中的元素数。
  • 我们继续在掩码中标记编码为序列的元素(如果选择了第 i 个索引元素,则在掩码中设置第 i 位)并继续检查当前选择的元素(当前和)是否为素数,如果它是素数并且所有其他元素都被访问,然后我们返回true ,我们得到了答案。
  • 否则,如果没有访问其他元素,那么由于当前和是素数,我们只需要搜索其他元素,这些元素可以单独或通过相加形成一些素数,因此我们可以安全地再次将当前和标记为 0。
  • 如果掩码已满(所有元素都被访问)并且当前和不是素数,我们返回false ,因为至少有一个和不是素数。
  • 复发
DP[mask] = solve(curr + arr[i], mask | 1<

下面是上述方法的实现。

C++
// C++ program to find the
// array of primes
#include 
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


Javascript


输出:
YES

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live