MHB Can Even Numbers Be Written as the Sum of Two Primes?

  • Thread starter Thread starter Ackbach
  • Start date Start date
  • Tags Tags
    2015
Ackbach
Gold Member
MHB
Messages
4,148
Reaction score
93
Here is this week's POTW:

-----

Write a computer program in Python or R to check, given a particular even integer, whether it can be written as the sum of two primes. (N.B., that this can be done for all even numbers greater than $2$ is the famous unproven Goldbach Conjecture.) The output should include a boolean: true if it can be done, and false if it cannot. If it can be done, output the two odd primes that sum to the input.

-----

Remember to read the http://www.mathhelpboards.com/showthread.php?772-Problem-of-the-Week-%28POTW%29-Procedure-and-Guidelines to find out how to http://www.mathhelpboards.com/forms.php?do=form&fid=2!
 
Physics news on Phys.org
So, ahem, Bacterius was supposed to solve this one, since he solved POTW # 164 - a highly related problem. But no one solved this week's POTW. I cobbled together this solution from Baterius's solution to POTW # 164 plus a tad bit more extra code I found and tweaked on the Internet. No doubt there are much more efficient methods of solution. For one, the sieve of Eratosthenes should be used to generate an array of prime numbers smaller than the input even number. Then you loop through that. Probably much more efficient for large input numbers. Still, this code runs quite fast up to $10^{11}$.

Code:
#!/usr/bin/env python3

# A primality test, following Ackbach's precise specifications.

class Result:
    def __init__(self, IsPrime, Error):
        self.IsPrime = IsPrime
        self.Error = Error

    @staticmethod
    def Error(msg):
        return Result(None, msg)

    @staticmethod
    def IsPrime():
        return Result(True, "")

    @staticmethod
    def IsNotPrime():
        return Result(False, "")

    def __repr__(self):
        return '(IsPrime={0}, Error="{1}")'.format(self.IsPrime,
                                                   self.Error)

def is_prime(n):
    if not isinstance(n, int):
        return Result.Error("an informative error message")

    if n <= 0:
        return Result.Error("a suitable error message")

    if n == 2:
        return Result.IsPrime()
    elif n == 1 or n % 2 == 0:
        return Result.IsNotPrime()
    else:
        divisor = 3

        while divisor * divisor <= n:
            if n % divisor == 0:
                return Result.IsNotPrime()
            else:
                divisor += 2

        return Result.IsPrime()

def findGolCon(num):
    answer1 = num // 2
    if is_prime(answer1).IsPrime:
        return answer1, answer1
    else:
        answer2 = answer1
        while not is_prime(answer1).IsPrime or not is_prime(answer2).IsPrime:
            answer1 -= 1
            answer2 += 1
        return answer1, answer2
 
Back
Top