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


Suppose we have a number n, we have to check whether n can be expressed as a sum of two semi-primes or not.

As we know the semi-prime is a number if it can be expressed as product of two primes number. First few semi-prime numbers are (1 - 100 range): 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.

So, if the input is like n = 108, then the output will be True as this is sum of 14 and 94 both are semi-prime.

To solve this, we will follow these steps −

  • MAX := 10000 assuming given inputs are sum of semi-primes which are in range 1 to 10000
  • nums := a new list
  • s_prime_flags := an array of size MAX and fill with False
  • Define a function get_semi_primes() . This will take
  • for i in range 2 to MAX - 1, do
    • count := 0
    • num := i
    • j := 2
    • while count < 2 and j^2 <= num, do
      • while num is divisible by j, do
        • num := num / j
        • count := count + 1
      • j := j + 1
    • if num > 1, then
      • count := count + 1
    • if count is same as 2, then
      • s_prime_flags[i] := True
  • insert i at the end of nums
  • From the main method do the following −
  • call get_semi_primes()
  • i := 0
  • while nums[i] <= quotient of (n / 2), do
    • if s_prime_flags[n - nums[i]] is True, then
      • return True
    • i := i + 1
  • return False

Let us see the following implementation to get better understanding −

Example

 Live Demo

MAX = 10000
nums = []
s_prime_flags = [False] * MAX
def get_semi_primes():
   for i in range(2, MAX):
      count = 0
      num = i
      j = 2
      while count < 2 and j * j <= num:
         while num % j == 0:
            num /= j
            count += 1
      j += 1
      if num > 1:
         count += 1
      if count == 2:
         s_prime_flags[i] = True
         nums.append(i)
def solve(n):
   get_semi_primes()
   i = 0
   while nums[i] <= n // 2:
      if s_prime_flags[n - nums[i]] == True:
         return True
      i += 1
   return False
n = 108
print(solve(n))

Input

[4, 2, 3], 11

Output

True

Updated on: 30-Dec-2020

508 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements