DEV Community

Cover image for Goldbach Conjecture Calculator
Scott Gordon
Scott Gordon

Posted on

Goldbach Conjecture Calculator

# goldbach_conjecture.py
#   The Goldbach conjecture asserts that every even number larger than 2 is the sum
#   of two prime numbers.
#   This program gets a number from the user, checks to make sure that it is
#   even, then finds two prime numbers that add up to the number inputted.
# by: Scott Gordon

from math import sqrt


def is_prime(n):
    """Determines whether number (n) is prime or not"""
    if n % 2 == 0 and n != 2:
        return False
    factor = 3
    while factor <= sqrt(n):
        if n % factor == 0:
            return False
        factor += 2
    return True


def goldbach(x):
    cand = 3
    while cand < x/2:
        other = x - cand
        if is_prime(cand) and is_prime(other):
            return cand
        else:
            cand = cand + 2


def main():
    print("Goldbach Conjecture Calculator\n")

    num = int(input("Enter an even natural number: "))
    if num % 2 != 0:
        print(f"{num} is not even!")
    else:
        prime1 = goldbach(num)
        prime2 = num - prime1
        print(f"{prime1} + {prime2} = {num}")


if __name__ == '__main__':
    main()
Enter fullscreen mode Exit fullscreen mode

Photo by Jeswin Thomas on Unsplash

Discussion (0)