Python :: Aufgabe #294 :: Lösung #1

2 Lösungen Lösungen öffentlich
#294

Goldbachsche Vermutung (binär)

Fortgeschrittener - Python von JKooP - 13.10.2020 um 08:32 Uhr
Die Goldbachsche Vermutung besagt, dass jede gerade Zahl größer 2 die Summe zweier Primzahlen ist.

1. Schreibe eine Funktion/Methode, die jeweils ein mögliches Primzahlenpaar bis zur Zahl 1000 ausgibt.

Beispiele:

4 = 2 + 2 -> (2, 2)
6 = 3 + 3 -> (3, 3)
8 = 3 + 5 -> (3, 5)

Duplikate durch Vertauschung wie z.B. (3, 5) -> (5, 3) sollen verhindert werden.

2. Schreibe eine Funktion/Methode, die alle mögliche Primzahlenpaare bis zur Zahl 1000 ausgibt.

Beispiele:

10 = 3 + 7 = 5 + 5 -> [ (3, 7), (5, 3) ]
14 = 3 + 11 = 7 + 7 -> [ (3, 11), (7, 7) ]

Viel Spaß
#1
vote_ok
von Marty3000 (680 Punkte) - 04.11.2020 um 09:11 Uhr
Quellcode ausblenden Python-Code
def get_prim(last: int):
    prim = [2]
    for i in range(prim[0], last):
        is_prim = True
        for p in prim:
            if is_prim and i % p == 0:
                is_prim = False
        if is_prim:
            prim.append(i)
    return prim


def goldbach(last: int, print_all: bool):
    if print_all:
        print("Alle Primzahlpaare")
    else:
        print("Nur ein Primzahlpaar")
    all_prim = get_prim(last)
    for i in range(4, last + 1, 2):
        txt: str = str(i)
        done: bool = False
        for p in all_prim:
            if not done and p <= i / 2 and all_prim.count(i - p) == 1:
                txt += " = %d + %d" % (p, i-p)
                done = not print_all
        print(txt)


if __name__ == '__main__':
    goldbach(1000, False)
    goldbach(1000, True)

Kommentare:

Für diese Lösung gibt es noch keinen Kommentar

Bitte melden Sie sich an um eine Kommentar zu schreiben.
Kommentar schreiben