Check whether the sum of prime elements of the array is prime or not in Python

When working with arrays containing numbers, we often need to identify prime numbers and perform operations on them. This problem requires us to find all prime elements in an array, sum them up, and check if that sum is also prime.

So, if the input is like nums = [1,2,4,5,3,3], then the output will be True as sum of all primes are (2+5+3+3) = 13 and 13 is also prime.

Understanding Prime Numbers

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. We'll use the Sieve of Eratosthenes algorithm to efficiently identify all primes up to a maximum value.

Algorithm Steps

To solve this problem, we will follow these steps:

  • Create a sieve array to mark prime numbers up to MAX (10000)
  • Use Sieve of Eratosthenes to generate all primes
  • Iterate through the input array and sum all prime elements
  • Check if the sum itself is prime

Implementation

MAX = 10000
sieve = [True] * MAX

def generate_list_of_primes():
    sieve[0] = False
    sieve[1] = False
    
    for i in range(2, MAX):
        if sieve[i]:
            for j in range(i * i, MAX, i):
                sieve[j] = False

def solve(arr):
    generate_list_of_primes()
    total = 0
    
    for num in arr:
        if num < MAX and sieve[num]:
            total += num
    
    if total < MAX and sieve[total]:
        return True
    return False

# Test the function
nums = [1, 2, 4, 5, 3, 3]
print("Array:", nums)
print("Result:", solve(nums))

# Let's also see which numbers are prime and their sum
def detailed_solution(arr):
    generate_list_of_primes()
    primes_in_array = []
    total = 0
    
    for num in arr:
        if num < MAX and sieve[num]:
            primes_in_array.append(num)
            total += num
    
    print(f"Prime numbers in array: {primes_in_array}")
    print(f"Sum of primes: {total}")
    print(f"Is sum prime? {total < MAX and sieve[total]}")
    return total < MAX and sieve[total]

detailed_solution(nums)
Array: [1, 2, 4, 5, 3, 3]
Result: True
Prime numbers in array: [2, 5, 3, 3]
Sum of primes: 13
Is sum prime? True

How the Sieve Works

The Sieve of Eratosthenes works by:

  • Starting with all numbers marked as prime (True)
  • Marking 0 and 1 as non-prime
  • For each prime number i, marking all its multiples (starting from i²) as non-prime

Testing with Different Arrays

# Test with different arrays
test_cases = [
    [1, 2, 4, 5, 3, 3],  # Primes: 2,5,3,3 ? Sum: 13 (prime)
    [4, 6, 8, 9],        # No primes ? Sum: 0 (not prime)
    [2, 3, 5, 7],        # Primes: 2,3,5,7 ? Sum: 17 (prime)
    [11, 13, 17],        # Primes: 11,13,17 ? Sum: 41 (prime)
]

for i, nums in enumerate(test_cases, 1):
    result = solve(nums)
    print(f"Test {i}: {nums} ? {result}")
Test 1: [1, 2, 4, 5, 3, 3] ? True
Test 2: [4, 6, 8, 9] ? False
Test 3: [2, 3, 5, 7] ? True
Test 4: [11, 13, 17] ? True

Key Points

  • The algorithm has O(n log log n) preprocessing time for sieve generation
  • Prime checking is then O(1) for each number
  • We need to handle edge cases where numbers exceed our MAX limit
  • The sum of primes could potentially be large, so bounds checking is important

Conclusion

This solution efficiently identifies prime numbers using the Sieve of Eratosthenes, sums all prime elements in the array, and checks if the sum is also prime. The approach is optimal for multiple queries on the same data structure.

Updated on: 2026-03-25T14:42:39+05:30

243 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements