23
\$\begingroup\$

Your task

Given two positive integers \$x\$ and \$d\$ (such that \$d<x\$), output the 5th term of the \$d\$th difference of the sequence \$n^x\$

Example

Let's say we are given the inputs \$x=4\$ and \$d=2\$.

First, we get the series \$n^4\$:

  • \$0^4 = 0\$
  • \$1^4 = 1\$
  • \$2^4 = 16\$
  • \$3^4 = 81\$
  • ...

These are the first 10 elements:

0 1 16 81 256 625 1296 2401 4096 6561

Now we work out the differences:

0 1 16 81 256 625 1296 2401  // Original series
 1 15 65 175 369 671 1105    // 1st difference
  14 50 110 194 302 434      // 2nd difference

Finally, we get the 5th term (1-indexed) and output:

302

Note: this is , so as long as the 5th term is somewhere in your output, it's fine.

Test cases

x  d  OUTPUT
4  2  302
2  1  9
3  2  30
5  3  1830

This Python program can be used to get the first three differences of any power series.

Rules

  • This is , so the input/output can be in any form.
  • This is , so shortest code in bytes wins!
\$\endgroup\$
4
  • \$\begingroup\$ Sandbox \$\endgroup\$
    – The Thonnu
    Commented Nov 1, 2022 at 11:47
  • \$\begingroup\$ Can you clarify "as long as the 5th term is somewhere in your output, it's fine"? In particular, can we output/return ALL sequences of 1..n-th differences for n≥d, so that the sequence of d-th differences is present and the 5th difference is shown (this would correspond to the full 'triangle' of differences in your second code-block, for instance)? \$\endgroup\$ Commented Nov 2, 2022 at 11:24
  • 5
    \$\begingroup\$ The literal interpretation of "as long as the 5th term is somewhere in your output, it's fine" implies that one could simply return a list of all integers, but that's clearly not what you intend (I assume...) \$\endgroup\$ Commented Nov 2, 2022 at 11:26
  • 1
    \$\begingroup\$ @DominicvanEssen - you may output the whole triangle. Outputting just a list of integers which has no relation to the challenge is forbidden. \$\endgroup\$
    – The Thonnu
    Commented Nov 2, 2022 at 11:49

29 Answers 29

13
\$\begingroup\$

R, 26 24 bytes

\(x,d)diff((0:5^d)^x,,d)

Attempt This Online!

Returns the first 5^d-d+1 elements (which is always ≥5) of d-th differences.

Obviously, for d>1 this includes a lot of unneccessary differences, but simply returning the first 5 elements is 2 1 byte* longer: \(x,d)diff((-d:4+d)^x,,d) (Attempt it here).

*Thanks to pajonk

\$\endgroup\$
2
  • \$\begingroup\$ -1 byte for the first-5-elements-alternative: \(x,d)diff((-d:4+d)^x,,d). \$\endgroup\$
    – pajonk
    Commented Nov 2, 2022 at 6:25
  • \$\begingroup\$ @pajonk - That's very neat! \$\endgroup\$ Commented Nov 2, 2022 at 6:43
8
\$\begingroup\$

Python, 53 bytes

f=lambda x,d,b=4:d and f(x,d-1,b+1)-f(x,d-1,b)or b**x

Attempt This Online!

Straight-forward recursion.

Python + NumPy, 50 bytes using builtin diff

lambda x,d:diff(r_[4:5+d]**x,d)
from numpy import*

Attempt This Online!

\$\endgroup\$
7
\$\begingroup\$

05AB1E, 7 6 bytes

∞ImIF¥

-1 byte thanks to @TheThonnu

Outputs the infinite sequence minus the first item. Inputs in the order \$x,d\$.

Try it online.

Explanation:

∞       # Push the infinite sequence of positive integers: [1,2,3,...]
 Im     # Takes each to the power of the first input
   IF   # Loop the second input amount of times:
     ¥  #  Get the deltas/forward-differences of the infinite list
        # (after which the infinite list is output implicitly)

Outputting the \$5^{th}\$ term would be 9 bytes instead by adding a trailing }3è (close the loop and get the 0-based 3rd item).

\$\endgroup\$
2
  • 1
    \$\begingroup\$ The < isn't necessary, because the 5th term will still be in your output without it. From the challenge: as long as the 5th term is somewhere in your output, it's fine. Try it online! \$\endgroup\$
    – The Thonnu
    Commented Nov 1, 2022 at 11:55
  • \$\begingroup\$ @TheThonnu Good point, thanks. :) \$\endgroup\$ Commented Nov 1, 2022 at 12:13
7
\$\begingroup\$

C (gcc), 112 bytes

j;i;*v;f(x,d){v=calloc(d+9,8);for(i=0;i<d+5;)v[i++]=pow(i,x);for(;d--;)for(j=0;j++<i;)v[j-1]-=v[j];x=abs(v[4]);}

Try it online!

This works on my machine with gcc version 13.0.0 but the return fails on TIO.

C (gcc), 66 60 bytes

q;f(x,d){q=x;g(d,4);}g(d,b){d=d--?g(d,b+1)-g(d,b):pow(b,q);}

Try it online!

Port of loopy walt's Python answer
Saved 6 bytes thanks to the man himself Arnauld!!!

Inputs \$x\$ and \$d\$.
Returns the \$5^\text{th}\$ term of the power sequence difference.

\$\endgroup\$
2
  • \$\begingroup\$ 60 bytes \$\endgroup\$
    – Arnauld
    Commented Nov 2, 2022 at 10:20
  • \$\begingroup\$ @Arnauld Very nice way to golf the parameters - thanks! :D \$\endgroup\$
    – Noodle9
    Commented Nov 2, 2022 at 10:47
6
\$\begingroup\$

Java, 127 90 bytes

x->d->g(x,d,4)double g(int x,int d,int k){return d>0?g(x,--d,k+1)-g(x,d,k):Math.pow(k,x);}

-37 bytes porting @loopyWalt's Python answer

Outputs the \$5^{th}\$ term like the test cases, except as double instead of int.

Try it online.

Explanation:

x->d->              // Method with two integer parameters and double return-type
  g(x,d,4)          //  Call the recursive method below with k=4

double g(int x,int d,int k){
                    // Recursive method with three integer parameters and double return
  return d>0?       //  If `d` is not 0:
    g(x,--d,k+1)    //   Do a recursive call with x, d-1, k+1
    -g(x,d,k)       //   Subtract a recursive call with x, d-1, k
   :                //  Else:
    Math.pow(k,x);} //   Calculate `k` to the power `x`
                    //   (which results in a double, hence the double return-type)
\$\endgroup\$
5
\$\begingroup\$

PARI/GP, 43 bytes

f(n,d)=polylog(-n,x)*(1-x)^d%x^(d+=5)\x^d--

Attempt This Online!

Using the polylogarithm \$\operatorname{Li}_{s}(x) = \sum_{k=1}^\infty\frac{x^k}{k^s}\$. When \$s=-n\$, this is the generating function of the sequence \$1^n, 2^n, 3^n, \dots\$. Taking the \$d\$th difference is just multiplying the generating function by \$(1-x)^d\$.

\$\endgroup\$
4
\$\begingroup\$

Vyxal, 7 bytes

Þ∞$e$(¯

Try it Online!

"Make infinite lists of numbers a digraph" they said. "It doesn't need to be 1 byte" they said. Well look where that got us :p. Could be 6 bytes in 2.4.1 but I don't know if it actually prints.

Explained

Þ∞$e$(¯
Þ∞$e    # [1 ** x, 2 ** x, 3 ** x, ...]
    $(  # d times:
      ¯ #   deltas
\$\endgroup\$
4
\$\begingroup\$

Excel (ms365), 143 bytes

=INDEX(REDUCE((ROW(1:1048576)-1)^A2,SEQUENCE(B2),LAMBDA(a,b,HSTACK(a,LET(c,TAKE(a,,-1),d,FILTER(c,ISNUMBER(c)),DROP(d,1)-DROP(d,-1))))),5,B2+1)

enter image description here

  • ROW(1:1048576)-1)^A2 - 1st Parameter in REDUCE() to have our 'n' thus 'infinite' (as many rows as possible in Excel) to the power of x;
  • SEQUENCE(B2) - The 2nd parameter of REDUCE() will tell the function to loop d-times;
  • LAMBDA(a,b,HSTACK(a,LET(c,TAKE(a,,-1),d,FILTER(c,ISNUMBER(c)),DROP(d,1)-DROP(d,-1)))) - The lambda helper function will keep pushing new columns with the difference between each value and it's predecessor;
  • The above is wrapped into INDEX() to grab the 5th element from the latest column.
\$\endgroup\$
4
\$\begingroup\$

Pyth, 9 bytes

.+F^Rvz+5

Try it online! or Test suite.

Input is in the form \$d\$ then \$x\$. Returns the first \$5\$ terms of the sequence.

Explanation:

.+F^Rvz+5QQ # Whole program. Implicit input Q (as d) added

    R       #  right map with lambda taking one argument:
   ^        #  using exponentiation
      z     #   the second input (x)
     v      #   evaluated
       +5Q  #  into implicit range(5 + d)
  F         # repeat the function
.+          # deltas
          Q #  d times
\$\endgroup\$
4
\$\begingroup\$

JavaScript (ES7), 38 bytes

Expects (x)(d). Same recursion as loopy walt in Python.

x=>g=(d,k=4)=>d--?g(d,k+1)-g(d,k):k**x

Try it online!

\$\endgroup\$
4
\$\begingroup\$

Charcoal, 28 27 bytes

NθNη≔E⁺⁵ηXιθζFηUMζ⁻κ§ζ⊖λI⊟ζ

Try it online! Link is to verbose version of code. Explanation:

NθNη

Input x and d.

≔E⁺⁵ηXιθζ

Generate d+5 xth powers.

FηUMζ⁻κ§ζ⊖λ

Generate differences d times.

I⊟ζ

Output the last difference (which is now the fifth).

\$\endgroup\$
4
\$\begingroup\$

sclin, 29 bytes

$W rev ^"."itr
2%`",_ - _"map

Try it here! Takes input n and returns an infinite list of infinite lists starting from d = 0.

For testing purposes:

5 ; >kv ( ,_ 10tk >A swap >o ": ">o f>o ) map 10tk >A
$W rev ^"."itr
2%`",_ - _"map

Explanation

Prettified code:

$W rev ^ \; itr
2%` ( ,_ - _ ) map

Assuming input d and n.

  • $W infinite range [0, ∞)
  • rev ^ i.e. range ^ n
  • \; itr successively apply next line to create infinite list
    • 2%` sliding pairs
    • ( ,_ - _ ) map difference of each pair
\$\endgroup\$
4
\$\begingroup\$

Desmos, 44 43 bytes

-1 byte thanks to Aiden Chow

f(n,d)=∑_{k=0}^d(-1)^{d-k}nCr(d,k)(k+4)^n

View it on Desmos.

Takes n and d as the inputs to a function f.

\$\endgroup\$
4
  • \$\begingroup\$ Nice, I rarely see Desmos answers by anyone else other than me! Unfortunately, input cannot be hard coded into variables like you have done here, as per meta consensus. You will have to make your code into a function by adding f(n,d)= or something similar to the beginning of the code. \$\endgroup\$
    – Aiden Chow
    Commented Nov 2, 2022 at 1:46
  • \$\begingroup\$ @AidenChow I fixed it though I'd be interested to know the rationale behind this. I can't seem to find any meta post about desmos i/o, just the one on scoring, if you could point me in the right direction I'd appreciate it. \$\endgroup\$ Commented Nov 2, 2022 at 18:51
  • \$\begingroup\$ codegolf.meta.stackexchange.com/q/2419 \$\endgroup\$
    – att
    Commented Nov 2, 2022 at 19:20
  • \$\begingroup\$ You can save one byte by replacing \sum with (see this tip). \$\endgroup\$
    – Aiden Chow
    Commented Nov 4, 2022 at 15:51
3
\$\begingroup\$

Ruby, 70 bytes

->x,d{s=(0..5**d+x).map{_1**x}
d.times{s=s.each_cons(2).map{_2-_1}}
s}

Attempt This Online!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Looks like recursive approach from Python answer is more promising in Ruby too: 45 bytes \$\endgroup\$
    – Kirill L.
    Commented Nov 2, 2022 at 12:23
  • \$\begingroup\$ @KirillL. Nice. That's pretty different from my solution, so feel free to post it as your own answer. \$\endgroup\$
    – Jordan
    Commented Nov 2, 2022 at 16:19
3
\$\begingroup\$

Clojure, 69 bytes

#(nth(iterate(fn[x](map -(rest x)x))(for[i(range)](Math/pow i %)))%2)

Try it online!

Returns the entire (lazy) sequence.

Clojure, 82 75 bytes

#(nth(nth(iterate(fn[x](map -(rest x)x))(for[i(range)](Math/pow i %)))%2)4)

Try it online!

Returns specifically the 5th term of the sequence.

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

J, 19 16 bytes

2&(-~/\)i.@+&5^]

Takes inspiration from Jelly. Accepts d as the left arg and x as the right arg.

-3 bytes thanks to Jonah

Attempt This Online!

2&(-~/\)i.@+&5^]
        i.@+&5^]  NB. dyadic fork
               ]  NB. returns right arg
        i.@+&5    NB. atop, +&5 adds five to left arg, i. creates a range 0..n-1
              ^   NB. raises each item of the range to y
2&(-~/\) ...      NB. dyadic hook
2&(-~/\)          NB. 2 -~/\ y computes the delta of adjacent elements
                  NB. ~ is necessary to flip the args since, for example, 1-16=_15
                  NB. x(n&u)y is a special form of ^:, it is equivalent to
                  NB. n&u^:x y, which applies n&u to y x times
\$\endgroup\$
2
  • \$\begingroup\$ Nice answer, -3 byte: 2&(-~/\)i.@+&5^] \$\endgroup\$
    – Jonah
    Commented Nov 1, 2022 at 22:29
  • 1
    \$\begingroup\$ @Jonah It all seems so obvious in retrospect haha. Nice save! \$\endgroup\$
    – south
    Commented Nov 2, 2022 at 0:17
3
\$\begingroup\$

Wolfram Language (Mathematica), 27 bytes

\!\(\_{i,#2}i^#\)/.i->4&

Try it online!

The private-use character is \[DifferenceDelta].

This character has code point U+F4A4, which is different from what the documentation (as of current writing) claims it to be. U+2206, the code point in documentation, corresponds to the similar-looking \[Laplacian]/ (undocumented).

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

Husk, 9 7 bytes

Edit: saved 2 bytes by outputting an infinite list of infinite lists, instead of just the d+1-th infinite list

¡Ẋ-m^⁰N

Try it online!

Returns an infinite list of infinite lists of differences of x-th powers.
The header in the TIO link extracts the d+1-th element of this, which is the infinite list of d-th differences.

    m       # map over
       N    # all integers 1..infinity
     ^⁰     # getting their x-th powers;
 ¡          # now, make an infinite list of infinite lists by repeatedly
  Ẋ-        # taking pairwise differences;
\$\endgroup\$
2
\$\begingroup\$

MathGolf, 6 bytes

úr▬kÄ│

Inputs in the order \$d,x\$. Outputs a list of the first \$10^{d}-d\$ amount of values, which gives a minimum of 9 terms (for \$d=1\$), including the \$5^{th}\$ term.

Try it online.

Explanation:

ú       # Push 10 to the power the first (implicit) input-integer `d`
 r      # Pop and push a list in the range [0,10ᵈ)
  ▬     # Take each value to the power of the second (implicit) input `x`
   k    # Push the first input `d` again
    Ä   # Loop that many times, using 1 character as inner code-block:
     │  #  Get the forward-differences of the list
        # (after which the entire stack is output implicitly as result)

A trailing (get 0-based 4th item) can be added to only output the \$5^{th}\$ term: try it online.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ @TheThonnu - why is this 'accepted' when it isn't the first answer to achieve 6 bytes? This one (also by Kevin) was. \$\endgroup\$ Commented Nov 2, 2022 at 11:28
2
\$\begingroup\$

Gaia, 13 bytes

:e…⟪¤*⟫¦@'ọ&e

Try it online!

I finally figured out how to do for loops in Gaia! Outputs approximately (10**x)-d terms (I think)

Explained

:e…⟪¤*⟫¦@'ọ&e
:e…           # Push range(0, x ** 10) to the stack
   ⟪¤*⟫¦      # and raise each item in that range to the power of x
       @'ọ&   # Repeat the string "ọ" d times (ọ is the deltas/forward differences command)
           e  # and execute that as Gaia code
\$\endgroup\$
2
\$\begingroup\$

Jelly, 7 bytes

+5Ḷ*I⁸¡

A dyadic Link that accepts \$d\$ on the left and \$x\$ on the right and yields a list of the first five terms.

Try it online!

How?

+5Ḷ*I⁸¡ - Link: integer, d; integer, x
+5      - (d) add five -> d+5
  Ḷ     - lowered range -> [0,1,2,...,d+4]
   *    - exponentiate (x) -> [0^x,1^x,2^x,...,(d+4)^x]
      ¡ - repeat...
     ⁸  - ...times: chain's left argument -> d
    I   - ...action: deltas
\$\endgroup\$
2
\$\begingroup\$

Perl 5, 65 bytes

sub f{my($x,$d,$p)=(@_,4);$d?f($x,--$d,$p+1)- f($x,$d,$p):$p**$x}

Try it online!

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

Factor, 54 49 47 bytes

[ dup 5 + iota rot v^n [ differences ] repeat ]

Returns the first 5 elements of the sequence.

Try it online!

                        ! 4 2
dup                     ! 4 2 2
5                       ! 4 2 2 5
+                       ! 4 2 7
iota                    ! 4 2 { 0 1 2 3 4 5 6 }
rot                     ! 2 { 0 1 2 3 4 5 6 } 4
v^n                     ! 2 { 0 1 16 81 256 625 1296 }
[ differences ] repeat  ! { 14 50 110 194 302 }
\$\endgroup\$
2
\$\begingroup\$

Nibbles, 8 7 bytes (14 nibbles)

`..,~^$@!>>$@-

Function that returns an infinite list of infinite lists of all differences of the x-th powers of all integers:

=@`..,~^$@!>>$@-
     ,~             # make a list 1..infinity
    .               # and map over each number
       ^$           # raising it to  
         @          # the arg1-th power;
  `.                # now iteratively apply this function:
          !         # zip together
           >>$      # this list without the first element
              @     # with itself
               -    # by subtraction (so: get differences)

To only output the d-th differences (as shown in the screenshot below) costs 1 byte (2 nibbles) more:

=                       # get the list at index
 @                      # arg2

enter image description here

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

MATLAB, 45 bytes

function f(x,d)
y=diff((0:5*d).^x,d);y(5)
end

Uses built-in diff function with the dth difference argument, outputs the fifth index of the resulting array.

Try it online!

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

Haskell, 50 bytes

can someone get rid of iterate?

x!d=iterate(zipWith(-)=<<tail)[n^x|n<-[0..]]!!d!!4

Try it online!

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

Haskell, 47 bytes

r x 0 i=i^x
r x d i=(r x(d-1)(i+1))-(r x(d-1)i)

Try it online!

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

><>, 89 bytes

Prints d*2 junk number in the beginning and another 2 junk numbers at the end.

:&5*>:0(?v:1-$:{:}\nao92*0.
:2(?v1-}$ :@*{    >
v~@~\02. >&:1-&1(?vl
>:2(    ?^1-@$:@$-}$

Try it online

><>, 94 bytes

Only prints numbers in the sequence.

:&5*>:0(?v:1-$:{:}c2.
 ~@~/01. >~{~v
:2(?^1-}$:@*{
  vlv?(1&-1:&<~~<
2:<$   }-$@:$@-1^?(
 oan<

Try it online

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

Scala, 198 bytes

Golfed version. Try it online!

def F(x:Int,d:Int)={val s=ListBuffer[Double]();for(i<-0 to(Math.pow(5,d)+x).toInt){s+=Math.pow(i,x)};for(_<-1 to d){s.indices.dropRight(1).foreach{i=>s(i)=s(i+1)-s(i)};s.remove(s.length-1)};s.toSeq}

Ungolfed version. Try it online!

import scala.collection.mutable.ListBuffer

object Main {
  def F(x: Int, d: Int): List[Double] = {
    val s = ListBuffer[Double]()
    for (i <- 0 to (Math.pow(5, d) + x).toInt) {
      s += Math.pow(i, x)
    }
    for (_ <- 1 to d) {
      s.indices.dropRight(1).foreach { i =>
        s(i) = s(i + 1) - s(i)
      }
      s.remove(s.length - 1)
    }
    s.toList
  }

  def main(args: Array[String]): Unit = {
    println(F(4, 2))
    println(F(2, 1))
    println(F(3, 2))
    println(F(5, 3))
  }
}

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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