Calculate power series result

17

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.

Luis felipe De jesus Munoz

Posted 2018-07-30T20:19:16.113

Reputation: 9 639

Question was closed 2018-07-31T10:08:35.587

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 than n. Since my vote hammers, I'll wait for others to say if this is dupe-worthy. – xnor – 2018-07-30T22:54:56.860

3@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 – 2018-07-31T02:36:12.320

This 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

Answers

9

R, 25 bytes

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

Try it online!

ngm

Posted 2018-07-30T20:19:16.113

Reputation: 3 974

2I love the way vectors work in R – Beta Decay – 2018-07-30T22:04:31.973

@BetaDecay maybe we should nominate R for the language of the month! – Giuseppe – 2018-07-31T01:56:14.800

1@giuseppe I've been thinking about that for a while now... let's target September? I'll post an answer in Meta. – JayCe – 2018-08-01T18:52:19.720

@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 :-) – Giuseppe – 2018-08-01T19:00:02.667

5

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!

flawr

Posted 2018-07-30T20:19:16.113

Reputation: 40 560

1also 21 bytes: x#0=1;x#n=x^n+x#(n-1). – nimi – 2018-07-30T22:21:51.040

@nimi Oh that is clever:) – flawr – 2018-07-31T18:07:24.967

5

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!

Arnauld

Posted 2018-07-30T20:19:16.113

Reputation: 111 334

x=>g=n=>n?g(n-1)*x+1:1 – tsh – 2018-07-31T05:36:10.653

5

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

Okx

Posted 2018-07-30T20:19:16.113

Reputation: 15 025

4

Jelly, 4 bytes

*Ż}S

Try it online!

Erik the Outgolfer

Posted 2018-07-30T20:19:16.113

Reputation: 38 134

Not sure it's worth another answer to post this other 4 byter: *ⱮS‘ – Jonathan Allan – 2018-07-30T21:09:06.403

@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 *...) – Erik the Outgolfer – 2018-07-30T21:27:16.103

3

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.

HyperNeutrino

Posted 2018-07-30T20:19:16.113

Reputation: 26 575

3

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.

AdmBorkBork

Posted 2018-07-30T20:19:16.113

Reputation: 41 581

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.

– mazzy – 2018-08-01T09:20:57.067

2 bytes less: param($x,$n,$s)0..$n|%{$s+=[math]::pow($x,$_)};$s. A caller still sends 2 parameters. – mazzy – 2018-08-01T10:16:47.673

1@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. – AdmBorkBork – 2018-08-01T12:33:07.470

3

MATL, 4 bytes

:^sQ

Try it online!

Takes input as N then X.

Giuseppe

Posted 2018-07-30T20:19:16.113

Reputation: 21 077

3

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

Beta Decay

Posted 2018-07-30T20:19:16.113

Reputation: 21 478

3

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)

Jonathan Allan

Posted 2018-07-30T20:19:16.113

Reputation: 67 804

The same to JS answer: +x**n -> *x+1 save 1 byte. – tsh – 2018-07-31T06:27:08.127

3

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.

sundar - Reinstate Monica

Posted 2018-07-30T20:19:16.113

Reputation: 5 296

2

Ruby, 26 bytes

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

Try it online!

Kirill L.

Posted 2018-07-30T20:19:16.113

Reputation: 6 693

2

Python 3, 42 bytes

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

Try it online!

Daniel

Posted 2018-07-30T20:19:16.113

Reputation: 6 425

Since x is guaranteed to be positive, I believe you can do if x<2. – Mario Ishac – 2018-07-31T02:02:19.790

@MarDev, ah yes that’s right. Thanks. – Daniel – 2018-07-31T02:12:42.743

2

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

Stephen

Posted 2018-07-30T20:19:16.113

Reputation: 12 293

2

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!

xnor

Posted 2018-07-30T20:19:16.113

Reputation: 115 687

2

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

Bubbler

Posted 2018-07-30T20:19:16.113

Reputation: 16 616

You can save 1 byte by using >: instead of 1+] 7 bytes

– Galen Ivanov – 2018-07-31T06:27:52.057

2

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.

tsh

Posted 2018-07-30T20:19:16.113

Reputation: 13 072

2

APL (Dyalog), 7 bytes

+/1,*∘⍳

Try it online!

Uriel

Posted 2018-07-30T20:19:16.113

Reputation: 11 708

1

Stax, 8 bytes

à╕F¬f£ù╞

Run and debug it

wastl

Posted 2018-07-30T20:19:16.113

Reputation: 3 089

1

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!

mbomb007

Posted 2018-07-30T20:19:16.113

Reputation: 21 944

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. – Jonathan Allan – 2018-07-30T22:24:40.410

1

Clean, 38 bytes

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

Try it online!

Οurous

Posted 2018-07-30T20:19:16.113

Reputation: 7 916

1

Pure Bash (no external utilities), 32

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

Try it online!

Digital Trauma

Posted 2018-07-30T20:19:16.113

Reputation: 64 644

1

Bash with GNU utilities, 23

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

Try it online!

Digital Trauma

Posted 2018-07-30T20:19:16.113

Reputation: 64 644

1

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

Jo King

Posted 2018-07-30T20:19:16.113

Reputation: 38 234

1

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

Luis Mendo

Posted 2018-07-30T20:19:16.113

Reputation: 87 464

1CJam... Now that's a name I haven't heard in a while – Beta Decay – 2018-07-31T09:29:05.347

@BetaDecay Judge me by my age, do you? – Luis Mendo – 2018-07-31T09:32:04.817

0

Pari/GP, 21 bytes

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

Try it online!

alephalpha

Posted 2018-07-30T20:19:16.113

Reputation: 23 988

You can take input via currying to save 1 byte. Demo.

– Mr. Xcoder – 2018-07-31T06:45:51.693

0

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

Kevin Cruijssen

Posted 2018-07-30T20:19:16.113

Reputation: 67 575

0

APL (Dyalog Classic), 8 bytes

⊣⊥1⍴⍨1+⊢

Try it online!

Galen Ivanov

Posted 2018-07-30T20:19:16.113

Reputation: 13 815

0

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!

qwertxzy

Posted 2018-07-30T20:19:16.113

Reputation: 101

0

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!

ErikF

Posted 2018-07-30T20:19:16.113

Reputation: 2 149

f(x,n,v){for(v=1;n--;v=v*x+1);x=v;} – tsh – 2018-07-31T07:20:33.587

f(b,e){b=e?pow(b,e--)+f(b,e):1;} – ceilingcat – 2018-07-31T14:27:12.820

0

Charcoal, 9 7 bytes

I↨NE⊕N¹

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

     N  Second input as a number
    ⊕   Increment
   E  ¹ Make list of `1`s of that length
  N     First input as a number
 ↨      Base conversion
I       Cast to string
        Implicitly print

Neil

Posted 2018-07-30T20:19:16.113

Reputation: 95 035

0

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)

ElPedro

Posted 2018-07-30T20:19:16.113

Reputation: 5 301

0

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.

Neil

Posted 2018-07-30T20:19:16.113

Reputation: 95 035

0

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!

Simone Chelo

Posted 2018-07-30T20:19:16.113

Reputation: 543