Python :: Aufgabe #335 :: Lösung #5

5 Lösungen Lösungen öffentlich
#335

Primfaktorzerlegung und Potenzschreibweise

Fortgeschrittener - Python von JKooP - 03.04.2021 um 09:53 Uhr
1. Schreibe eine Methode/Funktion, die jede Integer- Zahl in ihre Primfaktoren zerlegen kann
und das Ergebnis als Array/Liste zurückgibt.

Beispiel:
24 = 2*2*2*3

Lösung:
a = { 2, 2, 2, 3 }

2. Schreibe eine weitere Methode/Funktion, die die Werte des Arrays aus Aufgabe 1
in Potenzschreibweise überführt und auf dem Bildschirm ausgibt.
Das Zeichen zur Darstellung kann je nach Vorliebe/Programmiersprache variieren (^, **, h, ...).

Lösung:
2*2*2 = 2^3
3 = 3^1

Ausgabe:
2^3 * 3^1

Viel Spaß
#5
vote_ok
von vMaex (540 Punkte) - 19.04.2021 um 16:09 Uhr
Quellcode ausblenden Python-Code
prim = [2]
ar = []


def primCalculation(end):
    for i in range(3, end):
        a = 2
        isPrimCount = 0
        noPrimCount = 0
        while a < i:
            rest = i % a
            if rest != 0:
                a = a + 1
                isPrimCount = isPrimCount + 1
            else:
                noPrimCount = noPrimCount + 1
                a = a + 1
        if noPrimCount == 0 and isPrimCount > 0:
            prim.append(i)


def divide(number):
    primCalculation(number)
    y = 0
    for i in prim:
        next = False
        stop = False
        while type(y) == int and next is False and stop is False:
            y = number / i
            if str(y).endswith('.0') and stop is False:
                ar.append(i)
                y = int(y)
                number = y
                next = False
                if i > y:
                    stop = True
            else:
                y = y * i
                y = int(y)
                next = True
    print(ar) # 1. Ausgabe
    potenz() # 2. Ausgabe


def potenz():
    inhalt = []
    finalString = ''
    for i in ar:
        if i not in inhalt:
            inhalt.append(i)
    for i in inhalt:
        if ar.count(i) > 1:
            if finalString == '':
                finalString += str(i) + ' ^ ' + str(ar.count(i))
            else:
                finalString += ' + ' + str(i) + ' ^ ' + str(ar.count(i))
        else:
            if finalString == '':
                finalString += str(i) + ' ^ 1'
            else:
                finalString += ' + ' + str(i) + ' ^ 1'
    print(finalString)


divide(50)

Kommentare:

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

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