Quantcast
Channel: Programmierung – icancode.de
Viewing all articles
Browse latest Browse all 24

Größter gemeinsamer Teiler (iterativ)

$
0
0

Die Grundlagen und die rekursive Lösung habe ich ja bereits beschrieben. Der Vollständigkeit halber, hier noch die iterativen Lösungen:

Die alte Variante funktioniert wie folgt:

fun ggt(a: Int, b: Int): Int {
    var x = a
    var y = b
    if (a == 0) return b
    while (y != 0) {
        if (x > y) x -= y
        else y -= x
    }
    return x
} 

a und b müssen in separate, mutable Variablen überführt werden – also Felder, die veränderbar sind. Anschließend wird so lange eine Zahl von der anderen abgezogen, bis y = 0 ist.

Der moderne Algorithmus verwendet auch in der iterativen Implementierung den modulo Operator.

fun ggt(a: Int, b: Int): Int {
    var x = a
    var y = b
    while (y != 0) {
        val z = x.mod(y)
        x = y
        y = z
    }
    return x
}

Auch hier müssen die Parameter erst mutabel gemacht werden. Anschließend wird gerechnet. Das Ergebnis der Division mit Rest wird im Beispiel in dem Feld z zwischen gespeichert. Dieses kann immutable (unveränderbar) sein, da in jedem Schritt neu angelegt und nicht verändert wird. Natürlich ist auch eine Lösung möglich, die nur mutable Felder nutzt:

fun ggt(a: Int, b: Int): Int {
    var x = a
    var y = b
    var z: Int
    while (y != 0) {
        z = x.mod(y)
        x = y
        y = z
    }
    return x
}

Wie so oft sind die iterativen Implementierungen mehr Code als die rekursiven Lösungen. Dafür sind sie in der Regel einfacher lesbar bzw. nachvollziehbar, wenn der Algorithmus komplexer wird.

Der Artikel Größter gemeinsamer Teiler (iterativ) erschien zuerst auf icancode.de.


Viewing all articles
Browse latest Browse all 24

Trending Articles


Girasoles para colorear


mayabang Quotes, Torpe Quotes, tanga Quotes


Tagalog Quotes About Crush – Tagalog Love Quotes


OFW quotes : Pinoy Tagalog Quotes


Long Distance Relationship Tagalog Love Quotes


Tagalog Quotes To Move on and More Love Love Love Quotes


5 Tagalog Relationship Rules


Best Crush Tagalog Quotes And Sayings 2017


Re:Mutton Pies (lleechef)


FORECLOSURE OF REAL ESTATE MORTGAGE


Sapos para colorear


tagalog love Quotes – Tiwala Quotes


Break up Quotes Tagalog Love Quote – Broken Hearted Quotes Tagalog


Patama Quotes : Tagalog Inspirational Quotes


Pamatay na Banat and Mga Patama Love Quotes


Tagalog Long Distance Relationship Love Quotes


BARKADA TAGALOG QUOTES


“BAHAY KUBO HUGOT”


Vimeo 10.7.0 by Vimeo.com, Inc.


Vimeo 10.7.1 by Vimeo.com, Inc.