17
\$\begingroup\$

This question already has an answer here:

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.

\$\endgroup\$

marked as duplicate by Peter Taylor code-golf Jul 31 '18 at 10:08

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 4
    \$\begingroup\$ 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 =) \$\endgroup\$ – flawr Jul 30 '18 at 20:35
  • 3
    \$\begingroup\$ "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? \$\endgroup\$ – Jonathan Allan Jul 30 '18 at 21:25
  • 4
    \$\begingroup\$ 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. \$\endgroup\$ – xnor Jul 30 '18 at 22:54
  • 3
    \$\begingroup\$ @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. \$\endgroup\$ – Jo King Jul 31 '18 at 2:36
  • 2
    \$\begingroup\$ @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. \$\endgroup\$ – Peter Taylor Jul 31 '18 at 13:50

34 Answers 34

9
\$\begingroup\$

R, 25 bytes

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

Try it online!

\$\endgroup\$
  • 2
    \$\begingroup\$ I love the way vectors work in R \$\endgroup\$ – Beta Decay Jul 30 '18 at 22:04
  • \$\begingroup\$ @BetaDecay maybe we should nominate R for the language of the month! \$\endgroup\$ – Giuseppe Jul 31 '18 at 1:56
  • 1
    \$\begingroup\$ @giuseppe I've been thinking about that for a while now... let's target September? I'll post an answer in Meta. \$\endgroup\$ – JayCe Aug 1 '18 at 18:52
  • \$\begingroup\$ @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 :-) \$\endgroup\$ – Giuseppe Aug 1 '18 at 19:00
5
\$\begingroup\$

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
\$\endgroup\$
5
\$\begingroup\$

Haskell, 21 bytes

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!

\$\endgroup\$
  • 1
    \$\begingroup\$ also 21 bytes: x#0=1;x#n=x^n+x#(n-1). \$\endgroup\$ – nimi Jul 30 '18 at 22:21
  • \$\begingroup\$ @nimi Oh that is clever:) \$\endgroup\$ – flawr Jul 31 '18 at 18:07
5
\$\begingroup\$

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!

\$\endgroup\$
  • \$\begingroup\$ x=>g=n=>n?g(n-1)*x+1:1 \$\endgroup\$ – tsh Jul 31 '18 at 5:36
4
\$\begingroup\$

Jelly, 4 bytes

*Ż}S

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Not sure it's worth another answer to post this other 4 byter: *ⱮS‘ \$\endgroup\$ – Jonathan Allan Jul 30 '18 at 21:09
  • \$\begingroup\$ @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 *...) \$\endgroup\$ – Erik the Outgolfer Jul 30 '18 at 21:27
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

MATL, 4 bytes

:^sQ

Try it online!

Takes input as N then X.

\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

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)

\$\endgroup\$
  • \$\begingroup\$ The same to JS answer: +x**n -> *x+1 save 1 byte. \$\endgroup\$ – tsh Jul 31 '18 at 6:27
3
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – mazzy Aug 1 '18 at 9:20
  • \$\begingroup\$ 2 bytes less: param($x,$n,$s)0..$n|%{$s+=[math]::pow($x,$_)};$s. A caller still sends 2 parameters. \$\endgroup\$ – mazzy Aug 1 '18 at 10:16
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ – AdmBorkBork Aug 1 '18 at 12:33
2
\$\begingroup\$

Ruby, 26 bytes

->x,n{(0..n).sum{|i|x**i}}

Try it online!

\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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!

\$\endgroup\$
2
\$\begingroup\$

Python 3, 42 bytes

lambda x,n:n+1if x<2else(x**(n+1)-1)/(x-1)

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Since x is guaranteed to be positive, I believe you can do if x<2. \$\endgroup\$ – Mario Ishac Jul 31 '18 at 2:02
  • \$\begingroup\$ @MarDev, ah yes that’s right. Thanks. \$\endgroup\$ – Daniel Jul 31 '18 at 2:12
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ You can save 1 byte by using >: instead of 1+] 7 bytes \$\endgroup\$ – Galen Ivanov Jul 31 '18 at 6:27
2
\$\begingroup\$

APL (Dyalog), 7 bytes

+/1,*∘⍳

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Stax, 8 bytes

à╕F¬f£ù╞

Run and debug it

\$\endgroup\$
1
\$\begingroup\$

Clean, 38 bytes

import StdEnv
$x n=sum[x^i\\i<-[0..n]]

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Pure Bash (no external utilities), 32

echo $[`eval echo +$1**{0..$2}`]

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Bash with GNU utilities, 23

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

CJam, 8 bytes

l~),f#:+

Try it online! Or verify all test cases.

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
\$\endgroup\$
  • 1
    \$\begingroup\$ CJam... Now that's a name I haven't heard in a while \$\endgroup\$ – Beta Decay Jul 31 '18 at 9:29
  • \$\begingroup\$ @BetaDecay Judge me by my age, do you? \$\endgroup\$ – Luis Mendo Jul 31 '18 at 9:32
1
\$\begingroup\$

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!

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – Jonathan Allan Jul 30 '18 at 22:24
0
\$\begingroup\$

Pari/GP, 21 bytes

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

Try it online!

\$\endgroup\$
  • \$\begingroup\$ You can take input via currying to save 1 byte. Demo. \$\endgroup\$ – Mr. Xcoder Jul 31 '18 at 6:45
0
\$\begingroup\$

Java 8, 78 59 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
\$\endgroup\$
0
\$\begingroup\$

APL (Dyalog Classic), 8 bytes

⊣⊥1⍴⍨1+⊢

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$
0
\$\begingroup\$

C (gcc), 51 bytes

Your usual, everyday recursive solution.

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

Try it online!

\$\endgroup\$
  • \$\begingroup\$ f(x,n,v){for(v=1;n--;v=v*x+1);x=v;} \$\endgroup\$ – tsh Jul 31 '18 at 7:20
  • \$\begingroup\$ f(b,e){b=e?pow(b,e--)+f(b,e):1;} \$\endgroup\$ – ceilingcat Jul 31 '18 at 14:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.