You can directly estimate the amount without using the geometric progression formula. This has the advantage that division is not required (which is necessary if, for example, you want to adapt the code to return the result modulo some large number).
Let S (k) be the sum x ^ 0 + ... + x ^ {k-1}, it satisfies these recurrence relations:
S(1) = 1 S(2n) = S(n) * (1 + x^n) S(2n+1) = S(n) * (1 + x^n) + x^{2n}
Using them, the only difficulty is to keep the current xp value for use as x ^ n. Otherwise, the algorithm is very similar to the upward implementation of squaring.
#include <inttypes.h> #include <stdio.h> #include <stdint.h> int64_t exponent_sum(int64_t x, int64_t k) { int64_t r = 0, xp = 1; for (int i = 63; i >= 0; i--) { r *= 1 + xp; xp *= xp; if (((k + 1) >> i) & 1) { r += xp; xp *= x; } } return r; } int main(int argc, char *argv[]) { for (int k = 0; k < 10; k++) { printf("4^0 + 4^1 + ... + 4^%d = %" PRId64 "\n", k, exponent_sum(4, k)); } return 0; }
source share