简体   繁体   中英

Check whether a number can be expressed as a sum of two semi-prime numbers in Python

A semi-prime number is a number that can be expressed a product of two prime numbers. Example: 55 = 5 * 11

I'm trying to code a Python program that checks whether a number can be expressed as a sum of two semi-prime numbers (not necessarily distinct).

Example 1:

Input: 30
Output: Yes

Explanation: 30 can be expressed as 15 + 15, where 15 is a semi-prime number as it is a product of two prime numbers, 5 * 3.

Example 2:

Input: 62
Output: No

Explanation: Although, 62 is itself a semi-prime number (31 * 2), however, it cannot be expressed as sum of two semi-prime numbers.

Here is what I tried to do, but it doesn't work in all cases.

MAX = 200
arr = []
sprime = [False] * (MAX)

def computeSP():
    for i in range(2,MAX):
        cnt,num,j = 0,i,2
        while (cnt<2 and j*j <= num):
            while(num % j == 0):
                num = int(num/j)
                cnt = cnt + 1
            j = j+1

        if(num > 1):
            cnt = cnt + 1

        if(cnt == 2):
            sprime[i] = True
            arr.append(i)

def checkSP(n):
    i = 0
    while(arr[i] <= n/2):
        if(sprime[n - arr[i]]):
            return True
        i = i+1
    return False

computeSP()

n = int(input())

if(checkSP(n)):  
    print('Yes',end='')  
else:
    print('No',end='')  

62 as in the case you mentioned can be expressed as sum of 2 semi primes which is 58 and 4 ie 62 = 58+4 58 can be expressed as factors of 29,2 (prime numbers) 4 can be expressed as factors of 2,2 (prime numbers)

Hence, answer to your question is your logic is wrong because 62 can also be expressed in the similar way.

If you want the code then here you go:

import math
def factors(n):
    bool = False
    for i in range(2, n):
        if n % i == 0:
            a = i
            b = int(n / a)
            if prime_number(a) and prime_number(b):
                print("factors of ",n,"is",a,b)
                bool = True
                break
    return bool


def prime_number(m):
    prime = True
    for i in range(3, m):
        if m % i == 0:
            prime = False
            break
    return prime


if __name__ == '__main__':
    num = int(input())
    z = math.ceil(num/2)
    a = "NO"
    for i in range(1, z):
        x = i
        y = num - i
    if factors(x) and factors(y):
        print("diff x,y=", x, y)
        a = "YES"
        break
print(a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM