DEV Community

Cover image for Goldbach Conjecture Calculator
Scott Gordon
Scott Gordon

Posted on

1

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay