keon / algorithms

Minimal examples of data structures and algorithms in Python
MIT License
23.76k stars 4.59k forks source link

Add `Goldbach's conjecture` Algorithm #908

Open lemorage opened 7 months ago

lemorage commented 7 months ago

Goldbach's conjecture states that every even natural number greater than 2 is the sum of two prime numbers.

jaki729 commented 7 months ago
def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

def goldbach_conjecture(even_number):
    if even_number <= 2 or even_number % 2 != 0:
        print("Please provide an even number greater than 2.")
        return

    for i in range(2, even_number // 2 + 1):
        if is_prime(i) and is_prime(even_number - i):
            print(f"{even_number} = {i} + {even_number - i}")
            return

    print("Goldbach's conjecture is not applicable for this even number.")

# Example usage
even_number_to_check = 28  # Replace this with any even number greater than 2
goldbach_conjecture(even_number_to_check)
lemorage commented 7 months ago

There is already a prime_check function out of there, maybe using this would be better?

jaki729 commented 7 months ago

Yes, thats correct but using square root method used for the calculations of prime numbers is the effecient and loogical way for doing it as it is also good for large numbers or big integer values. And Goldbach's conjecture algorithm is the unsolved art of mathematics.

lemorage commented 7 months ago

Ya, quite reasonable, I agree.