Check if an integer can be expressed as a sum of two semi-primes in Python

A semi-prime number is a positive integer that can be expressed as the product of exactly two prime numbers (not necessarily distinct). For example, 4 = 2×2, 6 = 2×3, and 9 = 3×3 are semi-primes.

This problem asks us to determine if a given integer n can be expressed as the sum of two semi-prime numbers.

Understanding Semi-Prime Numbers

The first few semi-prime numbers in the range 1-100 are: 4, 6, 9, 10, 14, 15, 21, 22, 25, 26, 33, 34, 35, 38, 39, 46, 49, 51, 55, 57, 58, 62, 65, 69, 74, 77, 82, 85, 86, 87, 91, 93, 94, 95.

For example, if n = 108, the output should be True because 108 = 14 + 94, and both 14 (2×7) and 94 (2×47) are semi-primes.

Algorithm Steps

The solution follows these steps:

  • Generate all semi-prime numbers up to a maximum value (10000)
  • For each semi-prime number up to n/2, check if (n - semi-prime) is also a semi-prime
  • If such a pair exists, return True; otherwise, return False

Implementation

MAX = 10000
semi_primes = []
is_semi_prime = [False] * MAX

def generate_semi_primes():
    """Generate all semi-prime numbers up to MAX"""
    for i in range(2, MAX):
        count = 0
        num = i
        j = 2
        
        # Count prime factors
        while count < 2 and j * j <= num:
            while num % j == 0:
                num //= j
                count += 1
            j += 1
        
        # If there's a remaining factor greater than 1
        if num > 1:
            count += 1
        
        # If exactly 2 prime factors, it's a semi-prime
        if count == 2:
            is_semi_prime[i] = True
            semi_primes.append(i)

def can_express_as_sum_of_semi_primes(n):
    """Check if n can be expressed as sum of two semi-primes"""
    generate_semi_primes()
    
    # Check all semi-primes up to n/2
    for semi_prime in semi_primes:
        if semi_prime > n // 2:
            break
        
        complement = n - semi_prime
        if complement < MAX and is_semi_prime[complement]:
            return True
    
    return False

# Test the function
n = 108
result = can_express_as_sum_of_semi_primes(n)
print(f"Can {n} be expressed as sum of two semi-primes? {result}")

# Find the actual pair for demonstration
generate_semi_primes()
for semi_prime in semi_primes:
    if semi_prime > n // 2:
        break
    complement = n - semi_prime
    if complement < MAX and is_semi_prime[complement]:
        print(f"{n} = {semi_prime} + {complement}")
        break
Can 108 be expressed as sum of two semi-primes? True
108 = 14 + 94

How the Algorithm Works

The generate_semi_primes() function identifies semi-prime numbers by counting their prime factors. A number is semi-prime if it has exactly two prime factors (counting multiplicity).

The main function iterates through all semi-primes up to n/2 and checks if the complement (n - semi_prime) is also a semi-prime. This approach avoids checking duplicate pairs.

Example with Different Input

# Test with another number
n = 30
result = can_express_as_sum_of_semi_primes(n)
print(f"Can {n} be expressed as sum of two semi-primes? {result}")

# Find possible pairs
generate_semi_primes()
pairs = []
for semi_prime in semi_primes:
    if semi_prime > n // 2:
        break
    complement = n - semi_prime
    if complement < MAX and is_semi_prime[complement]:
        pairs.append((semi_prime, complement))

print(f"Possible pairs for {n}: {pairs}")
Can 30 be expressed as sum of two semi-primes? True
Possible pairs for 30: [(4, 26), (9, 21), (10, 20), (14, 16)]

Time Complexity

The time complexity is O(MAX × ?MAX) for generating semi-primes and O(number of semi-primes) for checking each input. The space complexity is O(MAX) for storing the boolean array and semi-prime list.

Conclusion

This algorithm efficiently determines if a number can be expressed as the sum of two semi-primes by pre-generating all semi-primes and using complement checking. The approach works well for numbers within the specified range and can be optimized further for larger inputs.

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

836 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements