📜  将N分解为满足给定条件的K个数的总和

📅  最后修改于: 2021-04-21 22:34:48             🧑  作者: Mango

给定整数N ,任务是将给定数字表示为K个数字的总和,其中至少K – 1个数字是不同的并且是2个质数的乘积。如果没有可能的答案,则打印-1

例子:

方法:请按照以下步骤解决问题:

  • 使用Eratosthenes筛将所有素数存储在向量中。
  • 遍历存储的质数,并将每对质数的乘积存储在另一个向量prod中。
  • 打印产品向量的前K – 1个元素
  • 如果prod向量的前K – 1个元素的总和大于N,则打印-1

下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
#include 
using namespace std;
  
// Vector to store prime numbers
vector primes;
  
// Function to generate prime
// numbers using SieveOfEratosthenes
void SieveOfEratosthenes()
{
    // Boolean array to store primes
    bool prime[10005];
  
    memset(prime, true, sizeof(prime));
  
    for (int p = 2; p * p <= 1000; p++) {
  
        // If p is a prime
        if (prime[p] == true) {
  
            // Mark all its multiples as non-prime
            for (int i = p * p; i <= 1000; i += p)
                prime[i] = false;
        }
    }
  
    // Print all prime numbers
    for (int p = 2; p <= 1000; p++)
        if (prime[p])
            primes.push_back(p);
}
  
// Function to generate n as the sum
// of k numbers where atleast K - 1
// are distinct and are product of 2 primes
void generate(int n, int k)
{
    // Stores the product of every
    // pair of prime number
    vector prod;
  
    SieveOfEratosthenes();
  
    int l = primes.size();
  
    for (int i = 0; i < l; i++) {
        for (int j = i + 1; j < l; j++) {
            if (primes[i] * primes[j] > 0)
                prod.push_back(primes[i]
                               * primes[j]);
        }
    }
  
    // Sort the products
    sort(prod.begin(), prod.end());
  
    int sum = 0;
    for (int i = 0; i < k - 1; i++)
        sum += prod[i];
  
    // If sum exceeds n
    if (sum > n)
        cout << "-1";
  
    // Otherwise, print the k
    // required numbers
    else {
        for (int i = 0; i < k - 1; i++) {
            cout << prod[i] << ", ";
        }
        cout << n - sum << "\n";
    }
}
  
// Driver Code
int main()
{
    int n = 52, k = 5;
    generate(n, k);
    return 0;
}


Java
// Java Program to implement
// the above approach
import java.util.*;
class GFG{
  
// Vector to store prime numbers
static Vector primes = new Vector<>();
  
// Function to generate prime
// numbers using SieveOfEratosthenes
static void SieveOfEratosthenes()
{
    // Boolean array to store primes
    boolean []prime = new boolean[10005];
    Arrays.fill(prime, true);
  
    for (int p = 2; p * p <= 1000; p++)
    {
  
        // If p is a prime
        if (prime[p] == true) 
        {
  
            // Mark all its multiples as non-prime
            for (int i = p * p; i <= 1000; i += p)
                prime[i] = false;
        }
    }
  
    // Print all prime numbers
    for (int p = 2; p <= 1000; p++)
        if (prime[p])
            primes.add(p);
}
  
// Function to generate n as the sum
// of k numbers where atleast K - 1
// are distinct and are product of 2 primes
static void generate(int n, int k)
{
    // Stores the product of every
    // pair of prime number
    Vector prod = new Vector<>();
    SieveOfEratosthenes();
  
    int l = primes.size();
  
    for (int i = 0; i < l; i++) 
    {
        for (int j = i + 1; j < l; j++) 
        {
            if (primes.get(i) * primes.get(j) > 0)
                prod.add(primes.get(i) * 
                         primes.get(j));
        }
    }
  
    // Sort the products
    Collections.sort(prod);
  
    int sum = 0;
    for (int i = 0; i < k - 1; i++)
        sum += prod.get(i);
  
    // If sum exceeds n
    if (sum > n)
        System.out.print("-1");
  
    // Otherwise, print the k
    // required numbers
    else
    {
        for (int i = 0; i < k - 1; i++) 
        {
            System.out.print(prod.get(i) + ", ");
        }
        System.out.print(n - sum + "\n");
    }
}
  
// Driver Code
public static void main(String[] args)
{
    int n = 52, k = 5;
    generate(n, k);
}
}
  
// This code is contributed by gauravrajput1


Python3
# Python3 program to implement
# the above approach
  
# list to store prime numbers
primes = []
  
# Function to generate prime
# numbers using SieveOfEratosthenes
def SieveOfEratosthenes():
  
    # Boolean array to store primes
    prime = [True] * 10005
  
    p = 2
    while p * p <= 1000:
  
        # If p is a prime
        if (prime[p] == True):
  
            # Mark all its multiples as non-prime
            for i in range(p * p, 1001, p):
                prime[i] = False
          
        p += 1
  
    # Print all prime numbers
    for p in range(2, 1001):
        if (prime[p]):
            primes.append(p)
  
# Function to generate n as the sum
# of k numbers where atleast K - 1
# are distinct and are product of 2 primes
def generate(n, k):
  
    # Stores the product of every
    # pair of prime number
    prod = []
  
    SieveOfEratosthenes()
  
    l = len(primes)
  
    for i in range(l):
        for j in range(i + 1, l):
            if (primes[i] * primes[j] > 0):
                prod.append(primes[i] * 
                            primes[j])
  
    # Sort the products
    prod.sort()
  
    sum = 0
    for i in range(k - 1):
        sum += prod[i]
  
    # If sum exceeds n
    if (sum > n):
        print ("-1")
  
    # Otherwise, print the k
    # required numbers
    else:
        for i in range(k - 1):
            print(prod[i], end = ", ")
              
        print(n - sum)
  
# Driver Code
if __name__ == "__main__":
      
    n = 52
    k = 5
      
    generate(n, k)
  
# This code is contributed by chitranayal


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
  
class GFG{
  
// List to store prime numbers
static List primes = new List();
  
// Function to generate prime
// numbers using SieveOfEratosthenes
static void SieveOfEratosthenes()
{
      
    // Boolean array to store primes
    bool []prime = new bool[10005];
    for(int i = 0; i < 10005; i++)
        prime[i] = true;
  
    for(int p = 2; p * p <= 1000; p++)
    {
  
        // If p is a prime
        if (prime[p] == true) 
        {
  
            // Mark all its multiples as non-prime
            for(int i = p * p; i <= 1000; i += p)
                prime[i] = false;
        }
    }
  
    // Print all prime numbers
    for(int p = 2; p <= 1000; p++)
        if (prime[p])
            primes.Add(p);
}
  
// Function to generate n as the sum
// of k numbers where atleast K - 1
// are distinct and are product of 2 primes
static void generate(int n, int k)
{
      
    // Stores the product of every
    // pair of prime number
    List prod = new List();
    SieveOfEratosthenes();
  
    int l = primes.Count;
  
    for(int i = 0; i < l; i++) 
    {
        for(int j = i + 1; j < l; j++) 
        {
            if (primes[i] * primes[j] > 0)
                prod.Add(primes[i] * 
                         primes[j]);
        }
    }
  
    // Sort the products
    prod.Sort();
  
    int sum = 0;
    for(int i = 0; i < k - 1; i++)
        sum += prod[i];
  
    // If sum exceeds n
    if (sum > n)
        Console.Write("-1");
  
    // Otherwise, print the k
    // required numbers
    else
    {
        for (int i = 0; i < k - 1; i++) 
        {
            Console.Write(prod[i] + ", ");
        }
        Console.Write(n - sum + "\n");
    }
}
  
// Driver Code
public static void Main(String[] args)
{
    int n = 52, k = 5;
      
    generate(n, k);
}
}
  
// This code is contributed by Amit Katiyar


输出:
6, 10, 14, 15, 7

时间复杂度: O(N log N)
辅助空间: O(N)