#include <math.h>
#include <stdint.h>
#include <stdlib.h>

#define likely(X) __builtin_expect(!!(X), 1)

uint64_t base_k_to_decimal(uint64_t *digits, uint64_t k, int num_digits)
{
    uint64_t result = 0;
    for (int i = 0; i < num_digits; ++i)
    {
        result += pow(k, i) * digits[num_digits - i - 1];
    }
    return result;
}

uint64_t* decimal_to_base_k(uint64_t decimal, uint64_t k)
{
    int num_digits;
    if (likely(k == 2))
        num_digits = log2(decimal) + 1;
    else
        num_digits = (log2(decimal)/log2(k)) + 1;

    uint64_t *result = calloc(num_digits + 1, sizeof(uint64_t));
    result[0] = num_digits + 1; // store the length as well

    for (int i = 0; decimal > 0; ++i)
    {
        result[num_digits - i] = decimal % k;
        decimal /= k;
    }

    return result;
}
