# Calculate power series result [duplicate]

Related: Calculate Power Series Coefficients

Given a positive integer $X$ and a max exponent (Also a positive integer too) $N$ calculate the result of a power series. Example:

$$X^0+X^1+X^2+\cdots +X^N$$

• Assume $(X + N) \le 100$

Test Cases

1 2  => 3
2 3  => 15
3 4  => 121
2 19 => 1048575


Standard rules apply.

• It 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 =) Jul 30, 2018 at 20:35
• "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? Jul 30, 2018 at 21:25
• This is the potential dupe I was thinking of, with a difference being that it goes to n*n-1 rather than n. Since my vote hammers, I'll wait for others to say if this is dupe-worthy.
– xnor
Jul 30, 2018 at 22:54
• @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 treat 0 as both positive and negative.
– Jo King
Jul 31, 2018 at 2:36
• @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 specific-question discussion question on meta. Jul 31, 2018 at 13:50

# R, 25 bytes

function(x,n)sum(x^(0:n))


Try it online!

• I love the way vectors work in R Jul 30, 2018 at 22:04
• @BetaDecay maybe we should nominate R for the language of the month! Jul 31, 2018 at 1:56
• @giuseppe I've been thinking about that for a while now... let's target September? I'll post an answer in Meta. Aug 1, 2018 at 18:52
• @JayCe yeah, sounds good. We should open up the R chatroom again (for the third time; I've twice opened one and both times it has died due to inactivity); I'm sure I'd love to add to whatever description you end up going with on the submission :-) Aug 1, 2018 at 19:00

# 05AB1E, 3 bytes

ÝmO


Try it online!

Explanation:

Input: 4, 3
Ý    [0..input] - [0, 1, 2, 3, 4]
m    Vectorized exponent - [1, 3, 9, 27, 81]
O    Sum - 121


The straightforward approach:

x#n=sum$map(x^)[0..n]  For the case $x \neq 1$ we alternatively could use following function with the same length: x#n=div(x*x^n-1)$x-1


This uses the fact that

$1 + x + x^2 + \ldots + x^n = \frac{x^{n+1} -1}{x-1} \forall x \neq 1.$

Try it online!

• also 21 bytes: x#0=1;x#n=x^n+x#(n-1).
– nimi
Jul 30, 2018 at 22:21
• @nimi Oh that is clever:) Jul 31, 2018 at 18:07

# JavaScript (ES6), 22 bytes

Saved 1 byte thanks to @tsh

x=>g=n=>~n&&x*g(n-1)+1


Try it online!

# Non-recursive (ES7), 23 bytes

Using the direct formula mentioned by @flawr:

x=>n=>~-(x**++n)/~-x||n


Try it online!

• x=>g=n=>n?g(n-1)*x+1:1
– tsh
Jul 31, 2018 at 5:36

# Jelly, 4 bytes

*Ż}S


Try it online!

• Not sure it's worth another answer to post this other 4 byter: *ⱮS‘ Jul 30, 2018 at 21:09
• @JonathanAllan I actually edited that away (note: I do this pretty often), but, eh, a grace period exists. :P (It was actually me forgetting about vectorization of *...) Jul 30, 2018 at 21:27

# Python 3, 40 bytes

lambda x,n:sum(x**k for k in range(n+1))


Try it online!

lambda x,n:sum(map(x.__pow__,range(n+1))) is cool too but it's 1 byte longer lol.

# MATL, 4 bytes

:^sQ


Try it online!

Takes input as N then X.

# Brachylog, 11 bytes

t⟦R&h;Rz^ᵐ+


Try it online!

Nothing particularly interesting, construct the range 0 to n, raise x to the power of each number in it.

And since I wanted to learn how ᵃccumulate works, here's a slightly longer version that uses that:

### 15 bytes

,1↺⟨t×{bh}⟩ᵃ⁾k+


Try it online!

Form array [1, x], and do this n times, accumulating the results into that array after each iteration: multiply the last element of the array, by the second element of the array (i.e. x). Since this calculates [1, x, x^2, ... x^n, x^(n+1)], knife off the last value and add the rest of them up as the output.

# Noether, 17 bytes

I~xI(ax!i^+~ai)aP


Try it online!

## Explanation

I~x               - Store the input in the variable x
I(         )   - Loop until the top of the stack equals the input n
a            - Push a
x           - Push x
!i         - Increment i
^        - Calculate the value of x^i
+~a     - Add x^i to a and store in a
i    - Push i
aP - Print the value of a


# 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)

• The same to JS answer: +x**n -> *x+1 save 1 byte.
– tsh
Jul 31, 2018 at 6:27

# PowerShell, 53 46 bytes

param($x,$n)0..$n|%{$o+=[math]::pow($x,$_)};$o  Try it online! Not bad for needing a .NET call for pow. -7 bytes thanks to mazzy. • It's stupid, but this param($x,$n)$s=0;0..$n|%{$s+=[math]::pow($x,$_)};$s is shorter. I don't sure about $s=0;: this expression is needed on a second run. Perhaps, it better to append ;rv s to the end. Aug 1, 2018 at 9:20
• 2 bytes less: param($x,$n,$s)0..$n|%{$s+=[math]::pow($x,$_)};$s. A caller still sends 2 parameters. Aug 1, 2018 at 10:16
• @mazzy Thanks! There's no need to re-initialize $s if it's run as a full program (e.g., how it's done on Try It Online), so that saves a few more bytes. Aug 1, 2018 at 12:33 # Ruby, 26 bytes ->x,n{(0..n).sum{|i|x**i}}  Try it online! # cQuents, 6 bytes $0;A^$ Try it online! # Explanation  Implicit inputs: A and n$0      Zero indexing
;     Output sum of first n terms in sequence
A^$Each term is A to the power of the current index  # Python, 31 bytes f=lambda x,n:n<1or x*f(x,n-1)+1  Try it online! Python 2, 33 bytes lambda x,n:1/x*-~n or~-x**-~n/~-x  Try it online! ## Python 3, 42 bytes lambda x,n:n+1if x<2else(x**(n+1)-1)/(x-1)  Try it online! • Since x is guaranteed to be positive, I believe you can do if x<2. Jul 31, 2018 at 2:02 • @MarDev, ah yes that’s right. Thanks. Jul 31, 2018 at 2:12 # Octave, 19 bytes @(x,n)sum(x.^(0:n))  Try it online! Just learnt Octave 15 minutes ago for this challenge... Hoping it is already optimized. # J, 8 7 bytes #.1$~>:


Try it online!

### How it works

#.1$~>: Left argument = X, Right argument = N 1$~>:  Generate a list of N+1 ones
#.       Interpret as base X digits and convert to single integer

• You can save 1 byte by using >: instead of 1+] 7 bytes Jul 31, 2018 at 6:27

# APL (Dyalog), 7 bytes

+/1,*∘⍳


Try it online!

# Stax, 8 bytes

à╕F¬f£ù╞


Run and debug it

# Clean, 38 bytes

import StdEnv
$x n=sum[x^i\\i<-[0..n]]  Try it online! # Pure Bash (no external utilities), 32 echo$[eval echo +$1**{0..$2}]


Try it online!

# Bash with GNU utilities, 23

seq -s+ -f$1^%g 0$2|bc


Try it online!

# Perl 6, 19 bytes

{sum $^a X**0..$^b}


Try it online!

### Explanation:

{                 }  # Anonymous code block
sum    # Get the sum of
X**   # The cross product with the meta operator exponential
$^a # With the first parameter 0..$^b  # And the range of 0 to the second parameter


# CJam, 8 bytes

l~),f#:+


### Explanation

l      e# Read a line from STDIN
~      e# Evaluate: pushes x, then n
)      e# Add 1 to n
,      e# Range: gives [0 1 ... n]
f#     e# Map with extra parameter: gives [x^0 x^1 ... x^n]
:+     e# Fold addition over array: gives x^0 + x^1 + ... + x^n
e# Implicit display in STDOUT

• CJam... Now that's a name I haven't heard in a while Jul 31, 2018 at 9:29
• @BetaDecay Judge me by my age, do you? Jul 31, 2018 at 9:32

# Python 2, 44 34 bytes

Here's my naive and simple solution.

f=lambda x,n:n>=0and x**n+f(x,n-1)


Try it online!

• r is redundant, so f=lambda x,n:n>=0and x**n+f(x,n-1) is 34, although golfing that with n>=0 -> ~n  we get my port of 33 bytes. Jul 30, 2018 at 22:24

# Pari/GP, 21 bytes

(x,n)->sum(i=0,n,x^n)


Try it online!

• You can take input via currying to save 1 byte. Demo. Jul 31, 2018 at 6:45

# Java 8, 7859 40 bytes

x->n->x>1?~-(int)Math.pow(x,n+1)/~-x:n+1


Uses the approach mentioned by @flawr.

Try it online.

Explanation:

x->n->                     // Method with two integer parameters and integer return-type
x>1?                     //  If x is larger than 1:
~-(int)Math.pow(x,n+1)  //   Return x to the power of n+1 - 1
/~-x                    //   integer-divided by x-1
:                        //  Else:
n+1                     //   Return n+1 as result instead


# APL (Dyalog Classic), 8 bytes

⊣⊥1⍴⍨1+⊢


Try it online!

# Prolog (SWI), 49 bytes

Throws errors, but still works I guess.

f(_,0,1).
f(X,N,Y):-M is N-1,f(X,M,Z),Y is Z+X^N.


Try it online!

# C (gcc), 51 bytes

f(b,e,t,i){for(t=1,i=e;i--;t*=b);t=e--?t+f(b,e):1;}


Try it online!

• f(x,n,v){for(v=1;n--;v=v*x+1);x=v;}
– tsh
Jul 31, 2018 at 7:20
• f(b,e){b=e?pow(b,e--)+f(b,e):1;} Jul 31, 2018 at 14:27