📜  给定数组中 K 个最小素数和合数的异或

📅  最后修改于: 2021-10-27 06:59:24             🧑  作者: Mango

给定一个由N个非零正整数和一个整数K 组成的数组arr[] ,任务是找到K 个最大素数和合数的异或。
例子:

方法:使用埃拉托色尼筛法生成一个布尔向量,其大小为数组中最大元素的大小,可用于检查数字是否为素数。
现在遍历数组和插入所有这些都是最小堆minHeapPrime和所有在最小堆minHeapNonPrime的合数素的数字。
现在,从两个最小堆中弹出前K 个元素并取这些元素的异或。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function for Sieve of Eratosthenes
vector SieveOfEratosthenes(int max_val)
{
    // Create a boolean vector "prime[0..n]". A
    // value in prime[i] will finally be false
    // if i is Not a prime, else true.
    vector prime(max_val + 1, true);
 
    // Set 0 and 1 as non-primes as
    // they don't need to be
    // counted as prime numbers
    prime[0] = false;
    prime[1] = false;
 
    for (int p = 2; p * p <= max_val; p++) {
 
        // If prime[p] is not changed, then
        // it is a prime
        if (prime[p] == true) {
 
            // Update all multiples of p
            for (int i = p * 2; i <= max_val; i += p)
                prime[i] = false;
        }
    }
    return prime;
}
 
// Function that calculates the xor
// of k smallest and k
// largest prime numbers in an array
void kMinXOR(int arr[], int n, int k)
{
    // Find maximum value in the array
    int max_val = *max_element(arr, arr + n);
 
    // Use sieve to find all prime numbers
    // less than or equal to max_val
    vector prime = SieveOfEratosthenes(max_val);
 
    // Max Heaps to store all the
    // prime and composite numbers
    priority_queue maxHeapPrime, maxHeapNonPrime;
 
    for (int i = 0; i < n; i++) {
 
        // If current element is prime
        if (prime[arr[i]]) {
             
            // Max heap will only store k elements
            if (maxHeapPrime.size() < k)
                maxHeapPrime.push(arr[i]);
   
            // If the size of max heap is K and the
            // top element is greater than the current
            // element than it needs to be replaced
            // by the current element as only
            // minimum k elements are required
            else if (maxHeapPrime.top() > arr[i]) {
                maxHeapPrime.pop();
                maxHeapPrime.push(arr[i]);
            }
        }
 
        // If current element is composite
        else if (arr[i] != 1) {
             
            // Heap will only store k elements
            if (maxHeapNonPrime.size() < k)
                maxHeapNonPrime.push(arr[i]);
   
            // If the size of max heap is K and the
            // top element is greater than the current
            // element than it needs to be replaced
            // by the current element as only
            // minimum k elements are required
            else if (maxHeapNonPrime.top() > arr[i]) {
                maxHeapNonPrime.pop();
                maxHeapNonPrime.push(arr[i]);
            }
        }
    }
 
    long long int primeXOR = 0, nonPrimeXor = 0;
    while (k--) {
 
        // Calculate the xor
        if (maxHeapPrime.size() > 0) {
            primeXOR ^= maxHeapPrime.top();
            maxHeapPrime.pop();
        }
 
        if (maxHeapNonPrime.size() > 0) {
            nonPrimeXor ^= maxHeapNonPrime.top();
            maxHeapNonPrime.pop();
        }
    }
 
    cout << "Prime XOR = " << primeXOR << "\n";
    cout << "Composite XOR = " << nonPrimeXor << "\n";
}
 
// Driver code
int main()
{
 
    int arr[] = { 4, 2, 12, 13, 5, 19 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3;
 
    kMinXOR(arr, n, k);
 
    return 0;
}


Java
// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
    // Function for Sieve of Eratosthenes
    static boolean[] SieveOfEratosThenes(int max_val)
    {
 
        // Create a boolean vector "prime[0..n]". A
        // value in prime[i] will finally be false
        // if i is Not a prime, else true.
        boolean[] prime = new boolean[max_val + 1];
        Arrays.fill(prime, true);
 
        // Set 0 and 1 as non-primes as
        // they don't need to be
        // counted as prime numbers
        prime[0] = false;
        prime[1] = false;
 
        for (int p = 2; p * p <= max_val; p++)
        {
 
            // If prime[p] is not changed, then
            // it is a prime
            if (prime[p])
            {
 
                // Update all multiples of p
                for (int i = p * 2; i <= max_val; i += p)
                    prime[i] = false;
            }
        }
 
        return prime;
    }
 
    // Function that calculates the sum
    // and product of k smallest and k
    // largest composite numbers in an array
    static void kMinXOR(Integer[] arr, int n, int k)
    {
 
        // Find maximum value in the array
        int max_val = Collections.max(Arrays.asList(arr));
 
        // Use sieve to find all prime numbers
        // less than or equal to max_val
        boolean[] prime = SieveOfEratosThenes(max_val);
 
        // Max Heap to store all the prime and composite numbers
        PriorityQueue maxHeapPrime =
                           new PriorityQueue((x, y) -> y - x);
        PriorityQueue maxHeapNonPrime =
                           new PriorityQueue((x, y) -> y - x);
 
        for (int i = 0; i < n; i++)
        {
 
            // If current element is prime
            if (prime[arr[i]])
            {
 
                // Max heap will only store k elements
                if (maxHeapPrime.size() < k)
                    maxHeapPrime.add(arr[i]);
 
                // If the size of max heap is K and the
                // top element is greater than the current
                // element than it needs to be replaced
                // by the current element as only
                // minimum k elements are required
                else if (maxHeapPrime.peek() > arr[i])
                {
                    maxHeapPrime.poll();
                    maxHeapPrime.add(arr[i]);
                }
            }
 
            // If current element is composite
            else if (arr[i] != -1)
            {
 
                // Heap will only store k elements
                if (maxHeapNonPrime.size() < k)
                    maxHeapNonPrime.add(arr[i]);
 
                // If the size of max heap is K and the
                // top element is greater than the current
                // element than it needs to be replaced
                // by the current element as only
                // minimum k elements are required
                else if (maxHeapNonPrime.peek() > arr[i])
                {
                    maxHeapNonPrime.poll();
                    maxHeapNonPrime.add(arr[i]);
                }
            }
        }
 
        long primeXOR = 0, nonPrimeXor = 0;
 
        while (k-- > 0)
        {
 
            // Calculate the xor
            if (maxHeapPrime.size() > 0)
            {
                primeXOR ^= maxHeapPrime.peek();
                maxHeapPrime.poll();
            }
 
            if (maxHeapNonPrime.size() > 0)
            {
                nonPrimeXor ^= maxHeapNonPrime.peek();
                maxHeapNonPrime.poll();
            }
        }
 
        System.out.println("Prime XOR = " + primeXOR);
        System.out.println("Composite XOR = " + nonPrimeXor);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        Integer[] arr = { 4, 2, 12, 13, 5, 19 };
        int n = arr.length;
        int k = 3;
 
        kMinXOR(arr, n, k);
    }
}
 
// This code is contributed by
// sanjeev2552


Python 3
from math import sqrt
# Python 3 implementation of the approach
 
# Function for Sieve of Eratosthenes
def SieveOfEratosthenes(max_val):
     
    # Create a boolean vector "prime[0..n]". A
    # value in prime[i] will finally be false
    # if i is Not a prime, else true.
    prime = [True for i in range(max_val + 1)]
 
    # Set 0 and 1 as non-primes as
    # they don't need to be
    # counted as prime numbers
    prime[0] = False
    prime[1] = False
 
    for p in range(2,int(sqrt(max_val)) + 1, 1):
         
        # If prime[p] is not changed, then
        # it is a prime
        if (prime[p] == True):
             
            # Update all multiples of p
            for i in range(p * 2,max_val+1,p):
                prime[i] = False
 
    return prime
 
# Function that calculates the xor
# of k smallest and k
# largest prime numbers in an array
def kMinXOR(arr, n, k):
     
    # Find maximum value in the array
    max_val = max(arr)
 
    # Use sieve to find all prime numbers
    # less than or equal to max_val
    prime = SieveOfEratosthenes(max_val)
 
    # Max Heaps to store all the
    # prime and composite numbers
    maxHeapPrime = []
    maxHeapNonPrime = []
 
    for i in range(n):
         
        # If current element is prime
        if (prime[arr[i]]):
 
            # Max heap will only store k elements
            if (len(maxHeapPrime) < k):
                maxHeapPrime.append(arr[i])
                maxHeapPrime.sort(reverse = True)
 
            # If the size of max heap is K and the
            # top element is greater than the current
            # element than it needs to be replaced
            # by the current element as only
            # minimum k elements are required
            elif(maxHeapPrime[0] > arr[i]):
                maxHeapPrime.remove(maxHeapPrime[0])
                maxHeapPrime.append(arr[i])
                maxHeapPrime.sort(reverse = True)
 
        # If current element is composite
        elif(arr[i] != 1):
             
            # Heap will only store k elements
            if (len(maxHeapNonPrime) < k):
                maxHeapNonPrime.append(arr[i])
                maxHeapNonPrime.sort(reverse = True)
 
            # If the size of max heap is K and the
            # top element is greater than the current
            # element than it needs to be replaced
            # by the current element as only
            # minimum k elements are required
            elif(maxHeapNonPrime[0] > arr[i]):
                maxHeapNonPrime.remove(maxHeapNonPrime[0])
                maxHeapNonPrime.append(arr[i])
                maxHeapNonPrime.sort(reverse = True)
 
    primeXOR = 0
    nonPrimeXor = 0
    while (k):
         
        # Calculate the xor
        if (len(maxHeapPrime) > 0):
            primeXOR ^= maxHeapPrime[0]
            maxHeapPrime.remove(maxHeapPrime[0])
 
        if (len(maxHeapNonPrime) > 0):
            nonPrimeXor ^= maxHeapNonPrime[0];
            maxHeapNonPrime.remove(maxHeapNonPrime[0])
         
        k -= 1
 
    print("Prime XOR = ",primeXOR)
    print("Composite XOR = ",nonPrimeXor)
 
# Driver code
if __name__ == '__main__':
    arr = [4, 2, 12, 13, 5, 19]
    n = len(arr)
    k = 3
 
    kMinXOR(arr, n, k);
 
# This code is contributed by Surendra_Gangwar


C#
// C# implementation of the approach 
using System;
using System.Collections.Generic;
class GFG
{
 
  // Function for Sieve of Eratosthenes
  static bool[] SieveOfEratosThenes(int max_val) 
  {
 
    // Create a boolean vector "prime[0..n]". A
    // value in prime[i] will finally be false
    // if i is Not a prime, else true.
    bool[] prime = new bool[max_val + 1];
    Array.Fill(prime, true);
 
    // Set 0 and 1 as non-primes as
    // they don't need to be
    // counted as prime numbers
    prime[0] = false;
    prime[1] = false;
 
    for (int p = 2; p * p <= max_val; p++) 
    {
 
      // If prime[p] is not changed, then
      // it is a prime
      if (prime[p]) 
      {
 
        // Update all multiples of p
        for (int i = p * 2; i <= max_val; i += p)
          prime[i] = false;
      }
    }
 
    return prime;
  }
 
  // Function that calculates the sum
  // and product of k smallest and k
  // largest composite numbers in an array
  static void kMinXOR(int[] arr, int n, int k) 
  {
 
    // Find maximum value in the array
    int max_val = arr[0];
    for(int i = 1; i < arr.Length; i++)
    {
      max_val = Math.Max(max_val, arr[i]);
    }
 
    // Use sieve to find all prime numbers
    // less than or equal to max_val
    bool[] prime = SieveOfEratosThenes(max_val);
 
    // Max Heap to store all the prime and composite numbers
    List maxHeapPrime =  new List();
    List maxHeapNonPrime =  new List();
    for (int i = 0; i < n; i++) 
    {
 
      // If current element is prime
      if (prime[arr[i]]) 
      {
 
        // Max heap will only store k elements
        if (maxHeapPrime.Count < k)
        {
          maxHeapPrime.Add(arr[i]);
          maxHeapPrime.Sort();
          maxHeapPrime.Reverse();
        }
 
        // If the size of max heap is K and the
        // top element is greater than the current
        // element than it needs to be replaced
        // by the current element as only
        // minimum k elements are required
        else if (maxHeapPrime[0] > arr[i]) 
        {
          maxHeapPrime.RemoveAt(0);
          maxHeapPrime.Add(arr[i]);
          maxHeapPrime.Sort();
          maxHeapPrime.Reverse();
        }
      }
 
      // If current element is composite
      else if (arr[i] != -1) 
      {
 
        // Heap will only store k elements
        if (maxHeapNonPrime.Count < k)
        {
          maxHeapNonPrime.Add(arr[i]);
          maxHeapNonPrime.Sort();
          maxHeapNonPrime.Reverse();
        }
 
        // If the size of max heap is K and the
        // top element is greater than the current
        // element than it needs to be replaced
        // by the current element as only
        // minimum k elements are required
        else if (maxHeapNonPrime[0] > arr[i])
        {
          maxHeapNonPrime.RemoveAt(0);
          maxHeapNonPrime.Add(arr[i]);
          maxHeapNonPrime.Sort();
          maxHeapNonPrime.Reverse();
        }
      }
    }
    long primeXOR = 0, nonPrimeXor = 0;
    while (k-- > 0) 
    {
 
      // Calculate the xor
      if (maxHeapPrime.Count > 0) 
      {
        primeXOR ^= maxHeapPrime[0];
        maxHeapPrime.RemoveAt(0);
      }
      if (maxHeapNonPrime.Count > 0) 
      {
        nonPrimeXor ^= maxHeapNonPrime[0];
        maxHeapNonPrime.RemoveAt(0);
      }
    }
    Console.WriteLine("Prime XOR = " + primeXOR);
    Console.WriteLine("Composite XOR = " + nonPrimeXor);
  }
 
  // Driver code
  static void Main() {
    int[] arr = { 4, 2, 12, 13, 5, 19 };
    int n = arr.Length;
    int k = 3;
 
    kMinXOR(arr, n, k);
  }
}
 
// This code is contributed by divyesh072019.


Javascript


输出:
Prime XOR = 10
Composite XOR = 8

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程