#1
28.02.2015 um 19:09 Uhr
Ich dachte, ich wäre bei C++
Die Mathematik dahinter war rechte einfach, daher habe ich zu Gunsten einer geringeren Laufzeit auf eine komplizierte Suche verzichtet.

Hier meine Lösung in C:
Quellcode ausblenden C-Code
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main() {
	long n, tmp;
	int i, m = 0;
	int* coeffs;
    printf("n: ");
    scanf("%ld", &n);
    tmp = n;
    if ((coeffs = malloc((int)ceil(log(2*n+1)/log(3)) * sizeof(int))) == NULL)
    	return 1; //Fehler bei Speicherreservierung
    while (tmp > 1) {
        switch (tmp % 3) {
            case 0: coeffs[m++] = 0; break;
            case 1: coeffs[m++] = 1; break;
            case 2: coeffs[m++] = -1; tmp++; break;
        }
        tmp /= 3;
    }
    coeffs[m] = 1;
     
    printf("n = %ld\n", n);
    printf("m = %d\n", m);
    printf("%ld =\n", n);
    for (i = m; i >= 0; i--)
    {
        if (coeffs[i] == 1)
            printf("+3**%d\n", i);
        else if (coeffs[i] == -1)
            printf("-3**%d\n", i);
    }
    return 0;
}
post_arrow
112 0