📜  找出其左右素数和相等的数组元素

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

给定一个大小为N的数组arr[] ,任务是在给定数组中找到其左侧素数之和等于其右侧素数之和的索引。

例子:

朴素的方法:最简单的方法是遍历数组并检查[0, N – 1]范围内每个索引的给定条件。如果发现任何索引的条件都为真,则打印该索引的值。

时间复杂度: O(N 2 *√M),其中M数组中最大的元素
辅助空间: O(1)

高效的方法:上述方法也可以使用埃拉托色尼筛法和前缀和技术进行优化,以将素数的和预先存储到数组元素的左右。请按照以下步骤解决问题:

  • 遍历数组以找到数组中存在的最大值。
  • 使用埃拉托色尼筛法找出小于或等于数组中存在的最大值的素数。将这些元素存储在 Map 中。
  • 初始化一个数组,比如first_array 。遍历数组并将所有素数的总和存储到first_array[i] 中的i索引。
  • 初始化一个数组,比如second_array 。反向遍历数组并将所有元素的总和存储到i索引的second_array[i]
  • 遍历数组first_arraysecond_array并检查是否在任何索引处,它们的值是否相等。如果发现为真,则返回该索引。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find an index in the
// array having sum of prime numbers
// to its left and right equal
int find_index(int arr[], int N)
{
    // Stores the maximum value
    // present in the array
    int max_value = INT_MIN;
 
    for (int i = 0; i < N; i++) {
        max_value = max(max_value, arr[i]);
    }
 
    // Stores all positive
    // elements which are <= max_value
    map store;
 
    for (int i = 1; i <= max_value; i++) {
        store[i]++;
    }
 
    // If 1 is present
    if (store.find(1) != store.end()) {
 
        // Remove 1
        store.erase(1);
    }
 
    // Sieve of Eratosthenes to
    // store all prime numbers which
    // are <= max_value in the Map
    for (int i = 2; i <= sqrt(max_value); i++) {
 
        int multiple = 2;
 
        // Erase non-prime numbers
        while ((i * multiple) <= max_value) {
 
            if (store.find(i * multiple) != store.end()) {
                store.erase(i * multiple);
            }
 
            multiple++;
        }
    }
 
    // Stores the sum of
    // prime numbers from left
    int prime_sum_from_left = 0;
 
    // Stores the sum of prime numbers
    // to the left of each index
    int first_array[N];
 
    for (int i = 0; i < N; i++) {
 
        // Stores the sum of prime numbers
        // to the left of the current index
        first_array[i] = prime_sum_from_left;
 
        if (store.find(arr[i]) != store.end()) {
 
            // Add current value to
            // the prime sum if the
            // current value is prime
            prime_sum_from_left += arr[i];
        }
    }
 
    // Stores the sum of
    // prime numbers from right
    int prime_sum_from_right = 0;
 
    // Stores the sum of prime numbers
    // to the right of each index
    int second_array[N];
 
    for (int i = N - 1; i >= 0; i--) {
 
        // Stores the sum of prime
        // numbers to the right of
        // the current index
        second_array[i] = prime_sum_from_right;
 
        if (store.find(arr[i]) != store.end()) {
 
            // Add current value to the
            // prime sum if the
            // current value is prime
            prime_sum_from_right += arr[i];
        }
    }
 
    // Traverse through the two
    // arrays to find the index
    for (int i = 0; i < N; i++) {
 
        // Compare the values present
        // at the current index
        if (first_array[i] == second_array[i]) {
 
            // Return the index where
            // both the values are same
            return i;
        }
    }
 
    // No index is found.
    return -1;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 11, 4, 7, 6, 13, 1, 5 };
 
    // Size of Array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << find_index(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.lang.*;
import java.util.*;
 
class GFG{
     
// Function to find an index in the
// array having sum of prime numbers
// to its left and right equal
static int find_index(int arr[], int N)
{
     
    // Stores the maximum value
    // present in the array
    int max_value = Integer.MIN_VALUE;
 
    for(int i = 0; i < N; i++)
    {
        max_value = Math.max(max_value, arr[i]);
    }
 
    // Stores all positive
    // elements which are <= max_value
    Map store= new HashMap<>();
 
    for(int i = 1; i <= max_value; i++)
    {
        store.put(i, store.getOrDefault(i, 0) + 1);
    }
 
    // If 1 is present
    if (store.containsKey(1))
    {
         
        // Remove 1
        store.remove(1);
    }
 
    // Sieve of Eratosthenes to
    // store all prime numbers which
    // are <= max_value in the Map
    for(int i = 2; i <= Math.sqrt(max_value); i++)
    {
        int multiple = 2;
 
        // Erase non-prime numbers
        while ((i * multiple) <= max_value)
        {
            if (store.containsKey(i * multiple))
            {
                store.remove(i * multiple);
            }
            multiple++;
        }
    }
 
    // Stores the sum of
    // prime numbers from left
    int prime_sum_from_left = 0;
 
    // Stores the sum of prime numbers
    // to the left of each index
    int[] first_array = new int[N];
 
    for(int i = 0; i < N; i++)
    {
         
        // Stores the sum of prime numbers
        // to the left of the current index
        first_array[i] = prime_sum_from_left;
 
        if (store.containsKey(arr[i]))
        {
 
            // Add current value to
            // the prime sum if the
            // current value is prime
            prime_sum_from_left += arr[i];
        }
    }
 
    // Stores the sum of
    // prime numbers from right
    int prime_sum_from_right = 0;
 
    // Stores the sum of prime numbers
    // to the right of each index
    int[] second_array= new int[N];
 
    for(int i = N - 1; i >= 0; i--)
    {
         
        // Stores the sum of prime
        // numbers to the right of
        // the current index
        second_array[i] = prime_sum_from_right;
 
        if (store.containsKey(arr[i]))
        {
             
            // Add current value to the
            // prime sum if the
            // current value is prime
            prime_sum_from_right += arr[i];
        }
    }
 
    // Traverse through the two
    // arrays to find the index
    for(int i = 0; i < N; i++)
    {
         
        // Compare the values present
        // at the current index
        if (first_array[i] == second_array[i])
        {
             
            // Return the index where
            // both the values are same
            return i;
        }
    }
 
    // No index is found.
    return -1;
}
 
// Driver code
public static void main(String[] args)
{
     
    // Given array arr[]
    int arr[] = { 11, 4, 7, 6, 13, 1, 5 };
     
    // Size of Array
    int N = arr.length;
     
    // Function Call
    System.out.println(find_index(arr, N));
}
}
 
// This code is contributed by offbeat


Python3
# Python3 program for the above approach
from math import sqrt
 
# Function to find an index in the
# array having sum of prime numbers
# to its left and right equal
def find_index(arr, N):
   
    # Stores the maximum value
    # present in the array
    max_value = -10**9
 
    for i in range(N):
        max_value = max(max_value, arr[i])
 
    # Stores all positive
    # elements which are <= max_value
    store = {}
 
    for i in range(1, max_value + 1):
        store[i] = store.get(i, 0) + 1
 
    # If 1 is present
    if (1 in store):
 
        # Remove 1
        del store[1]
 
    # Sieve of Eratosthenes to
    # store all prime numbers which
    # are <= max_value in the Map
    for i in range(2, int(sqrt(max_value)) + 1):
        multiple = 2
 
        # Erase non-prime numbers
        while ((i * multiple) <= max_value):
 
            if (i * multiple in store):
                del store[i * multiple]
 
            multiple += 1
 
 
    # Stores the sum of
    # prime numbers from left
    prime_sum_from_left = 0
 
    # Stores the sum of prime numbers
    # to the left of each index
    first_array = [0]*N
 
    for i in range(N):
       
        # Stores the sum of prime numbers
        # to the left of the current index
        first_array[i] = prime_sum_from_left
        if arr[i] in store:
           
            # Add current value to
            # the prime sum if the
            # current value is prime
            prime_sum_from_left += arr[i]
 
    # Stores the sum of
    # prime numbers from right
    prime_sum_from_right = 0
 
    # Stores the sum of prime numbers
    # to the right of each index
    second_array = [0]*N
 
    for i in range(N - 1, -1, -1):
       
        # Stores the sum of prime
        # numbers to the right of
        # the current index
        second_array[i] = prime_sum_from_right
 
        if (arr[i] in store):
            # Add current value to the
            # prime sum if the
            # current value is prime
            prime_sum_from_right += arr[i]
 
    # Traverse through the two
    # arrays to find the index
    for i in range(N):
       
        # Compare the values present
        # at the current index
        if (first_array[i] == second_array[i]):
 
            # Return the index where
            # both the values are same
            return i
 
    # No index is found.
    return -1
 
# Driver Code
if __name__ == '__main__':
    # Given array arr[]
    arr= [11, 4, 7, 6, 13, 1, 5]
 
    # Size of Array
    N = len(arr)
 
    # Function Call
    print (find_index(arr, N))
  
# This code is contributed by mohit kumar 29.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to find an index in the
// array having sum of prime numbers
// to its left and right equal
static int find_index(int[] arr, int N)
{
     
    // Stores the maximum value
    // present in the array
    int max_value = Int32.MinValue;
     
    for(int i = 0; i < N; i++)
    {
        max_value = Math.Max(max_value, arr[i]);
    }
 
    // Stores all positive
    // elements which are <= max_value
    Dictionary store = new Dictionary();
 
    for(int i = 1; i <= max_value; i++)
    {
        if (!store.ContainsKey(i))
            store[i] = 0;
             
        store[i]++;
    }
 
    // If 1 is present
    if (store.ContainsKey(1))
    {
         
        // Remove 1
        store.Remove(1);
    }
 
    // Sieve of Eratosthenes to
    // store all prime numbers which
    // are <= max_value in the Map
    for(int i = 2; i <= Math.Sqrt(max_value); i++)
    {
        int multiple = 2;
 
        // Erase non-prime numbers
        while ((i * multiple) <= max_value)
        {
            if (store.ContainsKey(i * multiple))
            {
                store.Remove(i * multiple);
            }
            multiple++;
        }
    }
 
    // Stores the sum of
    // prime numbers from left
    int prime_sum_from_left = 0;
 
    // Stores the sum of prime numbers
    // to the left of each index
    int[] first_array = new int[N];
 
    for(int i = 0; i < N; i++)
    {
         
        // Stores the sum of prime numbers
        // to the left of the current index
        first_array[i] = prime_sum_from_left;
 
        if (store.ContainsKey(arr[i]))
        {
             
            // Add current value to
            // the prime sum if the
            // current value is prime
            prime_sum_from_left += arr[i];
        }
    }
 
    // Stores the sum of
    // prime numbers from right
    int prime_sum_from_right = 0;
 
    // Stores the sum of prime numbers
    // to the right of each index
    int[] second_array = new int[N];
 
    for(int i = N - 1; i >= 0; i--)
    {
         
        // Stores the sum of prime
        // numbers to the right of
        // the current index
        second_array[i] = prime_sum_from_right;
 
        if (store.ContainsKey(arr[i]))
        {
             
            // Add current value to the
            // prime sum if the
            // current value is prime
            prime_sum_from_right += arr[i];
        }
    }
 
    // Traverse through the two
    // arrays to find the index
    for(int i = 0; i < N; i++)
    {
         
        // Compare the values present
        // at the current index
        if (first_array[i] == second_array[i])
        {
             
            // Return the index where
            // both the values are same
            return i;
        }
    }
     
    // No index is found.
    return -1;
}
 
// Driver Code
public static void Main()
{
     
    // Given array arr[]
    int[] arr = { 11, 4, 7, 6, 13, 1, 5 };
 
    // Size of Array
    int N = arr.Length;
 
    // Function Call
    Console.WriteLine(find_index(arr, N));
}
}
 
// This code is contributed by ukasp


Javascript


输出:
3

时间复杂度: O(N + max(arr[])loglog(max(arr[]))
辅助空间: O(max(arr[]) + N)

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