Paarumkehrung von Zahlen?

1 Antwort

#include <stdio.h>

typedef unsigned long int ul;

// Variante mit 2 Parametern
ul paartausch2( ul Eingabe, ul Ergebnis )        
{
    // Keine Fehlerbehandlung
    
    if( Eingabe == 0 )
        return Ergebnis;
        
    return paartausch2(Eingabe/100, Ergebnis*100 + Eingabe%100);
}

// Hilfsfunktionen für Variante mit nur einem Parameter.
// Der Code dieser Hilfsfunktionen wird wegen der 
// besseren Übersichtlichkeit hier nicht in den Code von // paartausch1() integriert.

#include <math.h>

// Cantorsche Paarungsfunktion
ul paar(ul x, ul y)
{
    return (x+y)*(x+y+1)/2 + y;
}

// Linke Umkehrfunktion zu Cantorscher Paarungsfunktion

ul links(ul z)
{
    ul j = sqrt(2*z + 0.25) - 0.5;
    return j - (z - j*(j+1)/2);
}

// Rechte Umkehrfunktion zu Cantorscher Paarungsfunktion

ul rechts(ul z)
{
    ul j = sqrt(2*z + 0.25) - 0.5;
    return z - j*(j+1)/2;
}    

ul paartausch0( ul Eingabe )    // Ohne Fehlerbehandlung
{
    ul x = links(Eingabe);
    ul y = rechts(Eingabe);
    
    if( x == 0 )
        return y;
        
    return paartausch0( paar(x/100, y*100 + x%100) );
}

// Variante mit nur einem Parameter.

ul paartausch1( ul Eingabe )
{
    // Keine Fehlerbehandlung

    return paartausch0( paar(Eingabe, 0) );
}

// Test

int main()
{
    printf("%ld\n", paartausch1(123456));    
    printf("%ld\n", paartausch1(5723981246));    

// Ausgabe: 
// 563412
// 4612982357

    return 0;
}



Woher ich das weiß:Studium / Ausbildung – LMU München, Dipl. Math., eigene Recherche