Python, 35 32 bytes
-1 Thanks to tsh (f(x,n-1)+x**n
-> f(x,n-1)*x+1
)
Port of Arnauld's Javascript answer - not sure if it is the first, so do shout if you know who deserves the credit!
f=lambda x,n:~n and f(x,n-1)+x**n
A recursive function which sums the terms right-to-left, with a base case of zero when n
reaches -1
(since ~(-1)
is -1 - (-1)
which is 0
which is falsey).
Try it online!
My previous 35 byter:
lambda x,n:x^1and~-x**-~n/~-x or-~n
Try it online!
How?
The ^
operator is bitwise-xor, so x^1
is zero when x
is one and non-zero otherwise.
In Python non-zeros are truthy, so the right of the logical and
is executed when x
is not one, but not executed when x
is one, whereupon the right of the logical or
is executed instead.
So, when x
is one we execute
-~n
which is equivalent to
-1 * ~n
which is equivalent to
-1 * (-1 - n)
which is equivalent to
1 + n
...
...and when x
is not one we execute
~-x**-~n/~-x
which, adding parentheses to signify precedence, is
(~-(x**(-~n)))/(~-x)
which is equivalent to
(-1 - -1 * (x ** (-1 * (-1 - n))))/(-1 - -x)
which is equivalent to
((x ** (n + 1)) - 1)/(x - 1)
4It would open up some more possibilities if we could assume that $ x\neq 1$, then we could use $ 1 + x + x^2 + \ldots + x^n = \frac{x^{n+1}-1}{x-1}$, but it is probably too late for that =) – flawr – 2018-07-30T20:35:44.450
I definitely remember this challenge appearing previously but I don't have time to look for a dupe now. – xnor – 2018-07-30T20:38:45.473
3"Assume 0 ≤ (X + N) ..." - but X & N are positive integers, so should that read "Assume 0 < (X + N) ..." or should X & N be non-negative integers? – Jonathan Allan – 2018-07-30T21:25:44.797
@JonathanAllan Most non-mathematicians would probably class zero as a positive integer – Beta Decay – 2018-07-30T21:58:14.173
1@BetaDecay really? Most non-mathematicians would probably class it as a "number" :p – Jonathan Allan – 2018-07-30T22:04:28.153
4This is the potential dupe I was thinking of, with a difference being that it goes to
n*n-1
rather thann
. Since my vote hammers, I'll wait for others to say if this is dupe-worthy. – xnor – 2018-07-30T22:54:56.8603@BetaDecay Most of the world considers
0
to be neither positive nor negative. A couple of places (like France) don't consider positive to mean strictly positive, and treat0
as both positive and negative. – Jo King – 2018-07-31T02:36:12.320This is a simply stated challenge with a clear title. Perhaps the other challenge with the irrelevant backstory and the confusing title should get the dupe label retroactively! – ngm – 2018-07-31T13:31:15.803
2@ngm, I don't find the title of this question clear, whereas the other title references a classic question that I've seen in printed puzzle books. However, if you want to propose flipping the duplicate closure relationship the place to do it is a [meta-tag:specific-question] [meta-tag:discussion] question on meta. – Peter Taylor – 2018-07-31T13:50:50.993