[Python] Goldbach's Conjecture - Find the number of ways an even number can be written as the...

Discussão em 'Python' iniciado por Stack, Fevereiro 23, 2025.

  1. Stack

    Stack Membro Participativo

    I want to know the number of ways that a given positive even number can be written as the sum of two primes.

    At the moment, I have this code:

    n = int(input(">"))
    def genprimes(n):#generate primes from 2 to n
    primes = []
    for i in range(2,n):
    prime = True
    for a in range(2,i):
    if i % a == 0:
    prime = False
    if prime == True:
    primes.append(i)
    return primes

    pairs = []
    primes = genprimes(n)

    for prime1 in primes:
    for prime2 in primes:
    if prime1 + prime2 == n and [prime1,prime2] not in pairs and [prime2,prime1] not in pairs:
    pairs.append([prime1,prime2])
    print(len(pairs))


    It works, but it becomes a little slow when n goes above 10,000 ish. Can anyone think of a more efficient way to find this value, so that it yields quick results for high values?

    Continue reading...

Compartilhe esta Página