内容中心

2026年评价高的四川高平整度模组端板定制加工厂家推荐-四川鑫佳盛铝业有限公司

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:

  1. Prime Check: A helper function to determine if a number is prime.
  2. 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

  1. 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.
  2. 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.

四川鑫佳盛铝业有限公司



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

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?