📜  非素数与数组素数的乘积的绝对差

📅  最后修改于: 2021-04-29 02:43:27             🧑  作者: Mango

给定一个正数数组,任务是计算非素数与素数的乘积之间的绝对差。

注意: 1既不是素数也不是非素数。

例子

Input : arr[] = {1, 3, 5, 10, 15, 7}
Output : 45
Explanation : Product of non-primes = 150
              Product of primes = 105

Input : arr[] = {3, 4, 6, 7} 
Output : 3

天真的方法:一个简单的解决方案是遍历数组并检查每个元素是否为素数。如果数字是素数,则将其乘以表示素数乘积的乘积P2,否则检查其是否不是1,然后将其乘以非素数的乘积,即P1。遍历整个数组后,取两者之间的绝对差(P1-P2)。
时间复杂度: O(N * sqrt(N))

高效方法:使用Eratosthenes筛子生成所有素数,直到数组的最大元素,并将它们存储在哈希中。现在,遍历数组并检查哈希图中是否存在该数字。然后,将这些数字乘以乘积P2,否则检查它是否不是1,然后将其乘以乘积P1。遍历整个数组后,显示两者之间的绝对差。

下面是上述方法的实现:

C++
// C++ program to find the Absolute Difference 
// between the Product of Non-Prime numbers 
// and Prime numbers of an Array 
    
#include  
using namespace std; 
    
// Function to find the difference between 
// the product of non-primes and the 
// product of primes of an array. 
int calculateDifference(int arr[], int n) 
{ 
    // 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 
    // Create a boolean array "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); 
    
    // Remaining part of SIEVE 
    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; 
        } 
    } 
    
    // Store the product of primes in P1 and 
    // the product of non primes in P2 
    int P1 = 1, P2 = 1; 
    for (int i = 0; i < n; i++) { 
    
        if (prime[arr[i]]) { 
    
            // the number is prime 
            P1 *= arr[i]; 
        } 
        else if (arr[i] != 1) { 
    
            // the number is non-prime 
            P2 *= arr[i]; 
        } 
    } 
    
    // Return the absolute difference 
    return abs(P2 - P1); 
} 
    
// Driver Code 
int main() 
{ 
    int arr[] = { 1, 3, 5, 10, 15, 7 }; 
    int n     = sizeof(arr) / sizeof(arr[0]); 
    
    // Find the absolute difference 
    cout << calculateDifference(arr, n); 
    
    return 0; 
}


Java
// Java program to find the Absolute Difference 
// between the Product of Non-Prime numbers 
// and Prime numbers of an Array 
import java.util.*;  
import java.util.Arrays; 
import java.util.Collections;
  
    
class GFG{
  
    // Function to find the difference between 
    // the product of non-primes and the 
    // product of primes of an array. 
    public static int calculateDifference(int []arr, int n) 
    { 
        // Find maximum value in the array 
  
        int max_val = Arrays.stream(arr).max().getAsInt();
        
        // USE SIEVE TO FIND ALL PRIME NUMBERS LESS 
        // THAN OR EQUAL TO max_val 
        // Create a boolean array "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);
        
        // Remaining part of SIEVE 
        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; 
            } 
        } 
        
        // Store the product of primes in P1 and 
        // the product of non primes in P2 
        int P1 = 1, P2 = 1; 
        for (int i = 0; i < n; i++) { 
        
            if (prime[arr[i]]) { 
        
                // the number is prime 
                P1 *= arr[i]; 
            } 
            else if (arr[i] != 1) { 
        
                // the number is non-prime 
                P2 *= arr[i]; 
            } 
        } 
        
        // Return the absolute difference 
        return Math.abs(P2 - P1); 
    } 
        
    // Driver Code 
    public static void main(String []args) 
    { 
        int[] arr = new int []{ 1, 3, 5, 10, 15, 7 }; 
        int n     = arr.length; 
        
        // Find the absolute difference 
        System.out.println(calculateDifference(arr, n)); 
        
        System.exit(0);
    } 
}
// This code is contributed 
// by Harshit Saini


Python3
# Python3 program to find the Absolute Difference 
# between the Product of Non-Prime numbers 
# and Prime numbers of an Array 
  
    
# Function to find the difference between 
# the product of non-primes and the 
# product of primes of an array. 
def calculateDifference(arr, n): 
    # Find maximum value in the array 
    max_val = max(arr)
    
    # USE SIEVE TO FIND ALL PRIME NUMBERS LESS 
    # THAN OR EQUAL TO max_val 
    # Create a boolean array "prime[0..n]". A 
    # value in prime[i] will finally be false 
    # if i is Not a prime, else true. 
  
    prime    = (max_val + 1) * [True]
    
    # Remaining part of SIEVE 
    prime[0] = False
    prime[1] = False
    p = 2
  
    while p * p <= max_val: 
  
        # 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
        p += 1
    
    # Store the product of primes in P1 and 
    # the product of non primes in P2 
    P1 = 1 ; P2 = 1
    for i in range(n):
  
        if prime[arr[i]]:
            # the number is prime 
            P1 *= arr[i]
  
        elif arr[i] != 1: 
            # the number is non-prime 
            P2 *= arr[i]
    
    # Return the absolute difference 
    return abs(P2 - P1)
    
# Driver Code 
if __name__ == '__main__':
    arr   = [ 1, 3, 5, 10, 15, 7 ] 
    n     = len(arr)
    
    # Find the absolute difference 
    print(calculateDifference(arr, n))
# This code is contributed 
# by Harshit Saini


C#
// C# program to find the Absolute Difference 
// between the Product of Non-Prime numbers 
// and Prime numbers of an Array 
using System;
using System.Linq;
    
class GFG{
  
    // Function to find the difference between 
    // the product of non-primes and the 
    // product of primes of an array. 
    static int calculateDifference(int []arr, int n) 
    { 
        // Find maximum value in the array 
        int max_val = arr.Max();
        
        // USE SIEVE TO FIND ALL PRIME NUMBERS LESS 
        // THAN OR EQUAL TO max_val 
        // Create a boolean array "prime[0..n]". A 
        // value in prime[i] will finally be false 
        // if i is Not a prime, else true. 
        var prime   = Enumerable.Repeat(true,
                                    max_val+1).ToArray();
        
        // Remaining part of SIEVE 
        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; 
            } 
        } 
        
        // Store the product of primes in P1 and 
        // the product of non primes in P2 
        int P1 = 1, P2 = 1; 
        for (int i = 0; i < n; i++) { 
        
            if (prime[arr[i]]) { 
        
                // the number is prime 
                P1 *= arr[i]; 
            } 
            else if (arr[i] != 1) { 
        
                // the number is non-prime 
                P2 *= arr[i]; 
            } 
        } 
        
        // Return the absolute difference 
        return Math.Abs(P2 - P1); 
    } 
        
    // Driver Code 
    public static void Main() 
    { 
        int[] arr = new int []{ 1, 3, 5, 10, 15, 7 }; 
        int n     = arr.Length; 
        
        // Find the absolute difference 
        Console.WriteLine(calculateDifference(arr, n)); 
    } 
}
// This code is contributed 
// by Harshit Saini


PHP


输出:
45

时间复杂度: O(N * log(log(N))
空间复杂度: O(MAX(N,max_val)),其中max_val是给定数组中元素的最大值。