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)
n*n-1
rather thann
. Since my vote hammers, I'll wait for others to say if this is dupe-worthy. \$\endgroup\$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. \$\endgroup\$