📜  数组的非素数和的素数之和的绝对差

📅  最后修改于: 2021-06-26 20:55:30             🧑  作者: Mango

给定一个正数数组,任务是计算非素数和素数之和之间的绝对差。
注意: 1既不是素数也不是非素数。
例子:

Input : 1 3 5 10 15 7
Output : 10
Explanation: Sum of non-primes = 25
             Sum of primes = 15

Input : 3 4 6 7 
Output : 0

天真的方法:一个简单的解决方案是遍历数组并检查每个元素是否为素数。如果数字是素数,则将其加到表示素数之和的和S2上,否则检查它是否不是1,然后将其加到非素数的总和中,比如说S1。遍历整个数组后,取两者之间的绝对差(S1-S2)。
时间复杂度:O(Nsqrt(N))
高效方法:使用Eratosthenes筛子生成所有素数,直到数组的最大元素,并将它们存储在哈希中。现在,遍历数组并检查哈希图中是否存在该数字。然后,将这些数字加到总和S2上,否则检查它是否不是1,然后将其加到总和S1上。
遍历整个数组后,显示两者之间的绝对差。
时间复杂度:O(Nlog(log(N))

C++
// C++ program to find the Absolute Difference
// between the Sum of Non-Prime numbers
// and Prime numbers of an Array
 
#include 
using namespace std;
 
// Function to find the difference between
// the sum of non-primes and the
// sum 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 sum of primes in S1 and
    // the sum of non primes in S2
    int S1 = 0, S2 = 0;
    for (int i = 0; i < n; i++) {
 
        if (prime[arr[i]]) {
 
            // the number is prime
            S1 += arr[i];
        }
        else if (arr[i] != 1) {
 
            // the number is non-prime
            S2 += arr[i];
        }
    }
 
    // Return the absolute difference
    return abs(S2 - S1);
}
 
int main()
{
 
    // Get the array
    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 Sum of
// Non-Prime numbers and Prime numbers
// of an Array
import java.util.*;
 
class GFG
{
 
// Function to find the difference
// between the sum of non-primes
// and the sum of primes of an array.
static int CalculateDifference(int arr[],
                               int n)
{
    // Find maximum value in the array
    int max_val = Integer.MIN_VALUE;
    for(int i = 0; i < n; i++)
    {
        if(arr[i] > max_val)
            max_val = arr[i];
    }
 
    // 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];
     
    for(int i = 0; i <= max_val; i++)
        prime[i] = 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 sum of primes in
    // S1 and the sum of non
    // primes in S2
    int S1 = 0, S2 = 0;
    for (int i = 0; i < n; i++)
    {
 
        if (prime[arr[i]])
        {
 
            // the number is prime
            S1 += arr[i];
        }
        else if (arr[i] != 1)
        {
 
            // the number is non-prime
            S2 += arr[i];
        }
    }
 
    // Return the absolute difference
    return Math.abs(S2 - S1);
}
 
// Driver Code
public static void main(String []args)
{
 
    // Get the array
    int arr[] = { 1, 3, 5, 10, 15, 7 };
    int n = arr.length;
 
    // Find the absolute difference
    System.out.println(CalculateDifference(arr, n));
}
}
 
// This code is contributed
// by ihritik


Python3
# Python3 program to find the Absolute
# Difference between the Sum of Non-Prime
# numbers and Prime numbers of an Array
import sys
 
# Function to find the difference
# between the sum of non-primes
# and the sum of primes of an array.
def CalculateDifference(arr, n):
 
    # Find maximum value in the array
    max_val = -1
    for i in range(0, n):
        if(arr[i] > max_val):
            max_val = arr[i]
     
    # 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 = [True for i in range(max_val + 1)]
 
    # 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 sum of primes in
    # S1 and the sum of non primes
    # in S2
    S1 = 0
    S2 = 0
    for i in range (0, n):
 
        if prime[arr[i]]:
 
            # the number is prime
            S1 += arr[i]
         
        elif arr[i] != 1:
 
            # the number is non-prime
            S2 += arr[i]
 
    # Return the absolute difference
    return abs(S2 - S1)
 
# Driver code
     
# Get the array
arr = [ 1, 3, 5, 10, 15, 7 ]
n = len(arr)
 
# Find the absolute difference
print(CalculateDifference(arr, n))
 
# This code is contributed
# by ihritik


C#
// C# program to find the Absolute
// Difference between the Sum of
// Non-Prime numbers and Prime
// numbers of an Array
using System;
 
class GFG
{
 
// Function to find the difference
// between the sum of non-primes
// and the sum of primes of an array.
static int CalculateDifference(int []arr,
                               int n)
{
    // Find maximum value in the array
    int max_val = int.MinValue;
    for(int i = 0; i < n; i++)
    {
        if(arr[i] > max_val)
            max_val = arr[i];
    }
 
    // 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.
    bool []prime = new bool[max_val + 1];
     
    for(int i = 0; i <= max_val; i++)
        prime[i] = 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 sum of primes in
    // S1 and the sum of non primes
    // in S2
    int S1 = 0, S2 = 0;
    for (int i = 0; i < n; i++)
    {
        if (prime[arr[i]])
        {
 
            // the number is prime
            S1 += arr[i];
        }
        else if (arr[i] != 1)
        {
 
            // the number is non-prime
            S2 += arr[i];
        }
    }
 
    // Return the absolute difference
    return Math.Abs(S2 - S1);
}
 
// Driver Code
public static void Main(string []args)
{
 
    // Get the array
    int []arr = { 1, 3, 5, 10, 15, 7 };
    int n = arr.Length;
 
    // Find the absolute difference
    Console.WriteLine(CalculateDifference(arr, n));
}
}
 
// This code is contributed
// by ihritik


PHP
 $max_val)
            $max_val = $arr[$i];
    }
 
    // 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 = array_fill(0, $max_val + 1, true);
 
    // Remaining part of SIEVE
    $prime[0] = false;
    $prime[1] = false;
     
    for ($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 ($i = $p * 2;
                 $i <= $max_val; $i += $p)
                $prime[$i] = false;
        }
    }
 
    // Store the sum of primes in
    // S1 and the sum of non
    // primes in S2
    $S1 = 0;
    $S2 = 0;
    for ($i = 0; $i < $n; $i++)
    {
 
        if ($prime[$arr[$i]])
        {
 
            // the number is prime
            $S1 += $arr[$i];
        }
        else if ($arr[$i] != 1)
        {
 
            // the number is non-prime
            $S2 += $arr[$i];
        }
    }
 
    // Return the absolute difference
    return abs($S2 - $S1);
}
 
// Driver code
     
// Get the array
$arr = array( 1, 3, 5, 10, 15, 7 );
$n = sizeof($arr);
 
// Find the absolute difference
echo CalculateDifference($arr, $n);
 
// This code is contributed
// by ihritik
?>


Javascript


输出:
10

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。