finding perfect pairs

Added: 2025-09-12 22:30:11

Question Image

finding perfect pairs

Answer

✏️ Edit
import math

def is_perfect_square(n):
    if n < 0:
        return False
    root = int(math.sqrt(n))
    return root * root == n

def is_perfect_cube(n):
    if n < 0:
        return False
    root = int(round(n ** (1/3)))
    return root ** 3 == n

def count_perfect_pairs(arr):
    n = len(arr)
    count = 0
    
    # Check all pairs (i, j) where i < j to avoid duplicates
    for i in range(n):
        for j in range(i + 1, n):
            sum_pair = arr[i] + arr[j]
            if is_perfect_square(sum_pair) or is_perfect_cube(sum_pair):
                count += 1
    
    return count

# Read input
t = int(input())
for _ in range(t):
    n = int(input())
    arr = list(map(int, input().split()))
    result = count_perfect_pairs(arr)
    print(result)