So my question is how to do this in C more specifically. I'm aware that O(logn) usually means that we'll be using recursion by somehow splitting one of the parameters.
What I'm trying to achieve is the sum of k = 0 to n of xn. for example exponent_sum(x, n) would be the parameters in this case.
Then,
exponent_sum(4, 4)
would be 40 + 41 + 42 + 43 + 44 = 341.
I'm not sure where to start. Some hints would be really appreciated.
One way to look at the sum is as a number in base x consisting of all 1s.
For e.g, 44 + 43 + 42 + 41 + 40 is 11111 in base 4.
In any base, a string of 1s is going to be equal to 1 followed by a string of the same number of 0s, minus 1, divided by the base minus 1.
For e.g:
etc
So put these together and we can generalize that
exponent_sum(x, n) = (x (n + 1) - 1) / (x - 1)
For example, exponent_sum(4, 4) = (45 - 1) / 3 = 1023 / 3 = 341
So the big O complexity for it will be the same as for computing xn
Let me add another proof for the sake of completeness:
s = 1 + x1 + x2 + ... + xn
Then
xs = x(1 + x1 + x2 + ... + xn) = x1 + x2 + ... + xn + xn+1 = s - 1 + xn+1
Solving for s
(x - 1)s = xn+1 - 1,
s = (xn+1 - 1)/(x - 1)
Another way to see the solution is like this: suppose the sum is S
written as
S = 1 + x + x^2 + ... + x^k
Then if we multiply both sides of it by x
we get
S*x = x * (1 + x + x^2 + ... + x^k)
= x + x^2 + ... + x^k + x^(k+1)
then add 1 to both sides
S*x + 1 = 1 + x + x^2 + ... + x^k + x^(k+1)
= (1 + x + x^2 + ... + x^k) + x^(k+1)
= S + x^(k+1)
which means
S*x - S = x^(k+1) - 1
S*(x - 1) = x^(k+1) - 1
so
S = (x^(k+1) - 1) / (x - 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With