To solve this problem, we need to count the number of pairs of elements in an array such that their sum is a prime number and the index of the first element is less than the index of the second element.
Approach
The solution involves two main steps:
- Prime Check: A helper function to determine if a number is prime.
- Pair Counting: Iterate over all valid pairs (i, j) where i < j, compute their sum, and check if it's prime using the helper function. Count the valid pairs.
Solution Code
def is_prime(s):
"""Check if a number is prime."""
if s <= 1:
return False
if s == 2:
return True
if s % 2 == 0:
return False
# Check divrs from 3 up to sqrt(s) (step 2 for odd numbers)
for i in range(3, int(s ** 0.5) + 1, 2):
if s % i == 0:
return False
return True
def count_prime_pairs(arr):
"""Count pairs (i,j) where i<j and sum is prime."""
count = 0
n = len(arr)
for i in range(n):
for j in range(i + 1, n):
if is_prime(arr[i] + arr[j]):
count += 1
return count
# Example usage
if __name__ == "__main__":
# Test case 1 (corrected example from problem statement)
arr1 = [1, 2, 4]
print(f"Number of prime pairs: {count_prime_pairs(arr1)}") # Output: 2
# Test case 2
arr2 = [1, 2, 3, 4]
print(f"Number of prime pairs: {count_prime_pairs(arr2)}") # Output:4
Explanation
-
Prime Check Function:
- Base Cases: Numbers ≤1 are not prime; 2 is the only even prime.
- Even Check: If the number is even (and not 2), it's not prime.
- Divr Check: For odd numbers, check divisibility from 3 up to the square root of the number (step 2 to skip even divrs). If any divr is found, the number is not prime.
-
Pair Counting:
- Iterate over all pairs (i, j) where i < j (to avoid duplicate pairs like (j,i)).
- For each pair, compute the sum and check if it's prime using the helper function.
- Increment the count if the sum is prime.
Key Notes
- Efficiency: The O(n²) approach works for small arrays (n ≤ 1000). For larger arrays, optimize by using frequency counts and precomputing primes up to the maximum possible sum (using sieve of Eratosthenes).
- Edge Cases: Handles empty arrays (returns 0), arrays with one element (returns0), and negative numbers (since sum of negatives can be ≤1, which is not prime).
This solution is straightforward and covers all basic cases, making it suitable for most programming problem constraints.

作者声明:本文包含人工智能生成内容。