# 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 =) Commented 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? Commented 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
Commented 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
Commented 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. Commented Jul 31, 2018 at 13:50

# Pyth, 14 13 bytes

AQVhH=+Z^GN)Z


Try it online!

How it works

assign('Q',eval_input())
assign('[G,H]',Q)
for N in num_to_range(head(H)):
assign('Z',plus(Z,Ppow(G,N)))
imp_print(Z)


## Batch, 61 bytes

@set s=0
@for /l %%i in (0,1,%2)do @set/as=s*%1+1
@echo %s%


Using @tsh's algorithm.

# Charcoal, 9 7 bytes

Ｉ↨ＮＥ⊕Ｎ¹


Try it online! Link is to verbose version of code. Uses @Bubbler's algorithm. Explanation:

     Ｎ  Second input as a number
⊕   Increment
Ｅ  ¹ Make list of 1s of that length
Ｎ     First input as a number
↨      Base conversion
Ｉ       Cast to string
Implicitly print


# Swift 4.0, 100 bytes

func a(x:Int,n:Int)->Int{return(0...n).reduce(0,{p,q in p+(q>=1 ?(1...q).reduce(1,{a,_ in a*x}):1)})}


Try it online!

### Ungolfed

func a(x:Int, n:Int) -> Int {
return (0...n).reduce(0,        // For 0 to n
{ p, q in                     // p is result of last cycle, q the current element
p +                         // Add p to
( q > 0 ?                   // If current element is not 0
(1...q).reduce(1, { a, _ in a*x } ) // pow(x, n) *
: 1                       // Otherwise, 1
)
}
)
}

* The reduce is shorter than:
import Foundation
[...] Int(pow(Double(x),Double(q)))


First golf I do, so could be much more golfable, but finally the super-verbose Swift has a chance to be used!