Patience, young "Padovan"

44

3

Everyone knows the Fibonacci sequence:
You take a square, attach an equal square to it, then repeatedly attach a square whose side length is equal to the largest side length of the resulting rectangle.
The result is a beautiful spiral of squares whose sequence of numbers is the Fibonacci sequence:

But, what if we didn't want to use squares?

If we use equilateral triangles—instead of squares—in a similar fashion, we get an equally beautiful spiral of triangles and a new sequence: the Padovan sequence, aka A000931:

Task:

Given a positive integer, \$N\$, output \$a_N\$, the \$N\$th term in the Padovan sequence OR the first \$N\$ terms.

Assume that the first three terms of the sequence are all \$1\$. Thus, the sequence will start as follows: $$ 1,1,1,2,2,3,... $$

Input:

  • Any positive integer \$N\ge0\$

  • Invalid input does not have to be taken into account

Output:

  • The \$N\$th term in the Padovan sequence OR the first \$N\$ terms of the Padovan sequence.

  • If the first \$N\$ terms are printed out, the output can be whatever is convenient (list/array, multi-line string, etc.)

  • Can be either \$0\$-indexed or \$1\$-indexed

Test Cases:
(0-indexed, \$N\$th term)

Input | Output
--------------
0     | 1
1     | 1
2     | 1
4     | 2
6     | 4
14    | 37
20    | 200
33    | 7739

(1-indexed, first \$N\$ terms)

Input | Output
--------------
1     | 1
3     | 1,1,1
4     | 1,1,1,2
7     | 1,1,1,2,2,3,4
10    | 1,1,1,2,2,3,4,5,7,9
12    | 1,1,1,2,2,3,4,5,7,9,12,16

Rules:

Tau

Posted 2019-04-07T20:21:05.717

Reputation: 1 935

214 (0-indexed) is shown as outputting 28 while I believe it should yield 37 – Jonathan Allan – 2019-04-07T20:53:08.170

@JonathanAllan yes, you are correct. I fixed the last two test cases for $N$th term but not that one. The post has been edited. – Tau – 2019-04-07T20:55:32.390

@LuisMendo I believe so. I'll edit the post. – Tau – 2019-04-08T13:06:25.653

Not to detract from the question, but is this the actual definition of the Fibonacci sequence? I was taught it as a sequence of numbers, in which the first two numbers are 1, and the 3rd and subsequent numbers are the sum of the prior two numbers. Then again, I was taught this as an example of a problem to solve with recursion... – sharur – 2019-04-08T23:30:19.333

1@sharur this definition for the Fibonacci sequence is the visual definition. Each successive square added has a length of that term in the sequence. The sequence you describe is the numerical reasoning behind it. Both sequences work just as well as the other. – Tau – 2019-04-09T02:12:33.303

1Note that the OEIS sequence you linked is slightly different, since it uses a_0=1, a_1=0, a_2=0. It ends up being shifted by a bit because then a_5=a_6=a_7=1 – Carmeister – 2019-04-09T02:13:04.680

@Carmeister yes, that is correct. The OEIS sequence is the true Padovan sequence, but I shifted it over to $a_0=a_1=a_2=1$ for convenience (plus most mentions I've seen of this sequence start it at the aforementioned shift). – Tau – 2019-04-09T02:17:40.773

Questions in Code Golf that result in answers under 10 bytes should automatically get a hat or something. Yet again the compact answers were mind boggling and it is hard to think that this question was not considered when the languages were developed. – KalleMP – 2019-04-09T22:35:33.350

Answers

59

Jelly, 10 bytes

9s3’Ẓæ*³FṀ

Try it online!

1-indexed. Computes the largest element of: $$\begin{bmatrix}0&0&1 \\ 1&0&1 \\ 0&1&0\end{bmatrix}^n$$ where the binary matrix is conveniently computed as: $$\begin{bmatrix}\mathsf{isprime}(0)&\mathsf{isprime}(1)&\mathsf{isprime}(2) \\ \mathsf{isprime}(3)&\mathsf{isprime}(4)&\mathsf{isprime}(5) \\ \mathsf{isprime}(6)&\mathsf{isprime}(7)&\mathsf{isprime}(8)\end{bmatrix}$$

(this is a total coincidence.)

9s3         [[1,2,3],[4,5,6],[7,8,9]]    9 split 3
   ’        [[0,1,2],[3,4,5],[6,7,8]]    decrease
    Ẓ       [[0,0,1],[1,0,1],[0,1,0]]    isprime
     æ*³    [[0,0,1],[1,0,1],[0,1,0]]^n  matrix power by input
        FṀ                               flatten, maximum

Lynn

Posted 2019-04-07T20:21:05.717

Reputation: 55 648

33this is clearly some kind of voodoo – Pureferret – 2019-04-08T10:51:31.273

7This should be published. – YSC – 2019-04-08T11:31:30.150

6

@YSC It has already been published in A000931. I'd never have guess the primes trick:)

– flawr – 2019-04-08T15:28:30.313

@flawr ho... I missed it – YSC – 2019-04-08T15:43:33.427

Funnily enough I saw this method on the OEIS page and thought there was no way it would be less than my 10 byte binomial sum method (turns out that guess was right, unless someone can golf a byte off this one!) – Jonathan Allan – 2019-04-08T16:06:36.453

1

...make that "unless someone can golf two bytes off this one" :) (now that I have a 9 byter)

– Jonathan Allan – 2019-04-08T16:39:38.673

1I'm so used to seeing absurdly small answers here, that I thought the comma after 'Jelly' was in fact the code for this problem – Tasos Papastylianou – 2019-04-09T15:33:14.283

@Pureferret The fact that the entries coincide with "isprime" is a coincidence, but using matrix powers to compute linear recurrence relations is a classical way to solve them.

– flawr – 2019-04-09T17:44:53.297

28

Oasis, 5 bytes

nth term 0-indexed

cd+1V

Try it online!

Explanation

   1V   # a(0) = 1
        # a(1) = 1
        # a(2) = 1
        # a(n) =
c       #        a(n-2)
  +     #              +
 d      #               a(n-3)

Emigna

Posted 2019-04-07T20:21:05.717

Reputation: 50 798

26

Jelly,  10 9  8 bytes

ŻṚm2Jc$S

A monadic Link accepting n (0-indexed) which yields P(n).

Try it online!

How?

Implements \$P(n) = \sum_{i=0}^{\lfloor\frac{n}2\rfloor}\binom{i+1}{n-2i}\$

ŻṚm2Jc$S - Link: integer, n       e.g. 20
Ż        - zero range                  [0, 1, 2, 3, 4, ..., 19, 20]
 Ṛ       - reverse                     [20, 19, ..., 4, 3, 2, 1, 0]
  m2     - modulo-slice with 2         [20, 18, 16, 14, 12, 10,  8,  6,  4,  2,  0]  <- n-2i
      $  - last two links as a monad:
    J    -   range of length           [ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11]  <- i+1
     c   -   left-choose-right         [ 0,  0,  0,  0,  0,  0,  0, 28,126, 45,  1]
       S - sum                         200

And here is a "twofer"
...a totally different method also for 8 bytes (this one is 1-indexed, but much slower):

3ḊṗRẎ§ċ‘ - Link: n
3Ḋ       - 3 dequeued = [2,3]
   R     - range = [1,2,3,...,n]
  ṗ      -   Cartesian power         [[[2],[3]],[[2,2],[2,3],[3,2],[3,3]],[[2,2,2],...],...]
    Ẏ    - tighten                   [[2],[3],[2,2],[2,3],[3,2],[3,3],[2,2,2],...]
     §   - sums                      [ 2,  3,   4,    5,    5,    6,     6,...]
       ‘ - increment                 n+1
      ċ  - count occurrences         P(n)

Jonathan Allan

Posted 2019-04-07T20:21:05.717

Reputation: 67 804

18

Haskell, 26 bytes

(l!!)
l=1:1:1:2:scanl(+)2l

Try it online! Outputs the n'th term zero-indexed.

I thought that the "obvious" recursive solution below would be unbeatable, but then I found this. It's similar to the classic golfy expression l=1:scanl(+)1l for the infinite Fibonacci list, but here the difference between adjacent elements is the term 4 positions back. We can more directly write l=1:1:zipWith(+)l(0:l), but that's longer.

If this challenge allowed infinite list output, we could cut the first line and have 20 bytes.

27 bytes

f n|n<3=1|1>0=f(n-2)+f(n-3)

Try it online!

xnor

Posted 2019-04-07T20:21:05.717

Reputation: 115 687

11

Python 2, 30 bytes

f=lambda n:n<3or f(n-2)+f(n-3)

Try it online!

Returns the n'th term zero indexed. Outputs True for 1.

xnor

Posted 2019-04-07T20:21:05.717

Reputation: 115 687

7

Wolfram Language (Mathematica), 33 bytes

a@0=a@1=a@2=1;a@n_:=a[n-2]+a[n-3]   

1-indexed, returns the nth term

Try it online!

J42161217

Posted 2019-04-07T20:21:05.717

Reputation: 15 931

6

J, 22 bytes

-2 bytes thanks to ngn and Galen

closed form, 26 bytes

0.5<.@+1.04535%~1.32472^<:

Try it online!

iterative, 22 bytes

(],1#._2 _3{ ::1])^:[#

Try it online!

Jonah

Posted 2019-04-07T20:21:05.717

Reputation: 8 729

1

Another 24-byte solution (boring) : (1#.2 3$:@-~])`1:@.(3&>) Try it online!

– Galen Ivanov – 2019-04-08T19:29:28.090

23 bytes thanks to ngn 1: -> # : Try it online!

– Galen Ivanov – 2019-04-08T20:06:00.073

@GalenIvanov tyvm, that's a great trick. – Jonah – 2019-04-08T20:56:58.830

21: -> 1. "adverse" works with a noun on the right, apparently – ngn – 2019-04-10T15:24:40.590

@ngn TIL... ty again! – Jonah – 2019-04-10T15:45:57.797

6

Octave / MATLAB, 35 33 bytes

@(n)[1 filter(1,'cbaa'-98,2:n<5)]

Outputs the first n terms.

Try it online!

How it works

Anonymous function that implements a recursive filter.

'cbaa'-98 is a shorter form to produce [1 0 -1 -1].

2:n<5 is a shorter form to produce [1 1 1 0 0 ··· 0] (n−1 terms).

filter(1,[1 0 -1 -1],[1 1 1 0 0 ··· 0]) passes the input [1 1 1 0 0 ··· 0] through a discrete-time filter defined by a transfer function with numerator coefficient 1 and denominator coefficients [1 0 -1 -1].

Luis Mendo

Posted 2019-04-07T20:21:05.717

Reputation: 87 464

5

Retina, 47 42 bytes

K`0¶1¶0
"$+"+`.+¶(.+)¶.+$
$&¶$.(*_$1*
6,G`

Try it online! Outputs the first n terms on separate lines. Explanation:

K`0¶1¶0

Replace the input with the terms for -2, -1 and 0.

"$+"+`.+¶(.+)¶.+$
$&¶$.(*_$1*

Generate the next n terms using the recurrence relation. *_ here is short for $&*_ which converts the (first) number in the match to unary, while $1* is short for $1*_ which converts the middle number to unary. The $.( returns the decimal sum of its unary arguments, i.e. the sum of the first and middle numbers.

6,G`

Discard the first six characters, i.e. the first three lines.

Neil

Posted 2019-04-07T20:21:05.717

Reputation: 95 035

5

Cubix, 20 bytes

This is 0 indexed and outputs the Nth term

;@UOI010+p?/sqq;W.\(

Try it online!

Wraps onto a cube with side length 2

    ; @
    U O
I 0 1 0 + p ? /
s q q ; W . \ (
    . .
    . .

Watch it run

  • I010 - Initiates the stack
  • +p? - Adds the top of stack, pulls the counter from the bottom of stack and tests
  • /;UO@ - If counter is 0, reflect onto top face, remove TOS, u-turn, output and halt
  • \(sqq;W - If counter is positive, reflect, decrement counter, swap TOS, push top to bottom twice, remove TOS and shift lane back into the main loop.

MickyT

Posted 2019-04-07T20:21:05.717

Reputation: 11 735

4

Python 2, 56 48 bytes

f=lambda n,a=1,b=1,c=1:n>2and f(n-1,b,c,a+b)or c

Try it online!

Returns nth value, 0-indexed.

Chas Brown

Posted 2019-04-07T20:21:05.717

Reputation: 8 959

4

Perl 6, 24 bytes

{(1,1,1,*+*+!*...*)[$_]}

Try it online!

A pretty standard generated sequence, with each new element generated by the expression * + * + !*. That adds the third-previous element, the second-previous element, and the logical negation of the previous element, which is always False, which is numerically zero.

Sean

Posted 2019-04-07T20:21:05.717

Reputation: 4 136

Why is this community wiki? – Jo King – 2019-04-07T23:14:27.600

@JoKing Beats me. If I did it somehow, it wasn't on purpose. – Sean – 2019-04-08T16:58:53.377

4

05AB1E, 8 bytes

1Ð)λ£₂₃+

Try it online!

Bear with me, I haven't golfed in a while. I wonder if there's a shorter substitute for 1Ð) which works in this case (I've tried 1D), 3Å1 etc. but none of them save bytes). Outputs the first \$n\$ terms of the sequence. Or, without the £, it would output an infinite stream of the terms of the sequence.

How?

1Ð)λ£₂₃+ | Full program.
1Ð)      | Initialize the stack with [1, 1, 1].
   λ     | Begin the recursive generation of a list: Starting from some base case,
         | this command generates an infinite list with the pattern function given.
    £    | Flag for λ. Instead of outputting an infinite stream, only print the first n.
     ₂₃+ | Add a(n-2) and a(n-3).

Mr. Xcoder

Posted 2019-04-07T20:21:05.717

Reputation: 39 774

I don't think 1Ð) can be 2 bytes tbh. I can think of six different 3-bytes alternatives, but no 2-byters.

– Kevin Cruijssen – 2019-04-08T10:02:34.690

4

K (ngn/k), 24 20 bytes

-4 bytes thanks to ngn!

{$[x<3;1;+/o'x-2 3]}

Try it online!

0-indexed, first N terms

Galen Ivanov

Posted 2019-04-07T20:21:05.717

Reputation: 13 815

1f[x-2]+f[x-3] -> +/o'x-2 3 (o is "recur") – ngn – 2019-04-08T18:04:59.570

@ngn Thanks! I tried it (without success) in J; it's elegant here. – Galen Ivanov – 2019-04-08T18:54:42.413

@ngn In fact here's one possibillity how it looks in J: (1#.2 3$:@-~])`1:@.(3&>) – Galen Ivanov – 2019-04-08T19:32:10.350

ah, right, base-1 decode is a train-friendly way to sum :) – ngn – 2019-04-08T19:35:54.673

21: -> # in the j solution – ngn – 2019-04-08T19:44:09.393

@ngn # is a nice golf! Now it's 23 bytes and beats Jonah's J solution :) – Galen Ivanov – 2019-04-08T20:04:55.073

Boo! :) @ngn thanks for that # trick – Jonah – 2019-04-08T20:18:51.617

4

APL (Dyalog Unicode), 20 18 17 bytesSBCS

This code is 1-indexed. It's the same number of bytes to get n items of the Padovan sequence, as you have to drop the last few extra members. It's also the same number of bytes to get 0-indexing.

Edit: -2 bytes thanks to ngn. -1 byte thanks to ngn

4⌷2(⊢,⍨2⌷+/)⍣⎕×⍳3

Try it online!

Explanation

4⌷2(⊢,⍨2⌷+/)⍣⎕×⍳3

  ⍺(. . . .)⍣⎕⍵   This format simply takes the input ⎕ and applies the function
                   inside the brackets (...) to its operands (here marked ⍵ and ⍺).
  2(. . .+/)⍣⎕×⍳3  In this case, our ⍵, the left argument, is the array 1 1 1,
                   where we save our results as the function is repeatedly applied
                   and our ⍺, 2, is our right argument and is immediately applied to +/,
                   so that we have 2+/ which will return the pairwise sums of our array.
       2⌷          We take the second pairwise sum, f(n-2) + f(n-3)
    ⊢,⍨            And add it to the head of our array.
4⌷                 When we've finished adding Padovan numbers to the end of our list,
                   the n-th Padovan number (1-indexed) is the 4th member of that list,
                   and so, we implicitly return that.

Sherlock9

Posted 2019-04-07T20:21:05.717

Reputation: 11 664

4

x86 32-bit machine code, 17 bytes

53 33 db f7 e3 43 83 c1 04 03 d8 93 92 e2 fa 5b c3

Disassembly:

00CE1250 53                   push        ebx  
00CE1251 33 DB                xor         ebx,ebx  
00CE1253 F7 E3                mul         eax,ebx  
00CE1255 43                   inc         ebx  
00CE1256 83 C1 04             add         ecx,4  
00CE1259 03 D8                add         ebx,eax  
00CE125B 93                   xchg        eax,ebx  
00CE125C 92                   xchg        eax,edx  
00CE125D E2 FA                loop        myloop (0CE1259h)  
00CE125F 5B                   pop         ebx  
00CE1260 C3                   ret

It is 0-indexed. The initialization is conveniently achieved by calculating eax * 0. The 128-bit result is 0, and it goes in edx:eax.

At the beginning of each iteration, the order of the registers is ebx, eax, edx. I had to choose the right order to take advantage of the encoding for the xchg eax instruction - 1 byte.

I had to add 4 to the loop counter in order to let the output reach eax, which holds the function's return value in the fastcall convention.

I could use some other calling convention, which doesn't require saving and restoring ebx, but fastcall is fun anyway :)

anatolyg

Posted 2019-04-07T20:21:05.717

Reputation: 10 719

2I love to see machine code answers on PP&CG! +1 – Tau – 2019-04-09T02:14:48.623

3

Jelly, 11 bytes

5B+Ɲ2ị;Ʋ⁸¡Ḣ

Try it online!

0-indexed.

Erik the Outgolfer

Posted 2019-04-07T20:21:05.717

Reputation: 38 134

3

JavaScript (ES6), 23 bytes

Implements the recursive definition of A000931, but with \$a(0)=a(1)=a(2)=1\$, as specified in the challenge.

Returns the \$N\$th term, 0-indexed.

f=n=>n<3||f(n-2)+f(n-3)

Try it online!

Arnauld

Posted 2019-04-07T20:21:05.717

Reputation: 111 334

I don't think it's reasonable to say that returning true is the same as returning 1 if the rest of the output is numbers. – Nit – 2019-04-08T12:27:25.427

2

@Nit Relevant meta post.

– Arnauld – 2019-04-08T12:30:04.337

I think you are missing some requirements: Have a look at my modification (version in Java) here.

– Shaq – 2019-04-09T09:43:29.760

@Shaq The challenge clearly specifies that the first three terms of the sequence are all 1. So, it's not the sequence defined in A000931 (but the formula is the same). – Arnauld – 2019-04-09T09:49:35.103

@Arnauld yep I can see it now. Sorry! – Shaq – 2019-04-09T11:22:47.433

With 24 votes against 16 + 4 votes, looks like the community has accepted true as valid here. But if you don't like that, you can make the first three terms explicitly 1 by adding an extra byte: f=x=>x<3?1:f(x-2)+f(x-3) – eedrah – 2019-04-10T07:45:14.720

3

Lua 5.3, 49 48 bytes

function f(n)return n<4 and 1or f(n-2)+f(n-3)end

Try it online!

Vanilla Lua doesn't have coercion of booleans to strings (even tonumber(true) returns nil), so you have to use a pseudo-ternary operator. This version is 1-indexed, like all of Lua. The 1or part has to be changed to 1 or in Lua 5.1, which has a different way of lexing numbers.

cyclaminist

Posted 2019-04-07T20:21:05.717

Reputation: 191

3

Ruby, 26 bytes

f=->n{n<3?1:f[n-2]+f[n-3]}

Try it online!

G B

Posted 2019-04-07T20:21:05.717

Reputation: 11 099

2

Japt -N, 12 bytes

<3ªßUµ2 +ß´U

Try it

Embodiment of Ignorance

Posted 2019-04-07T20:21:05.717

Reputation: 7 014

Looks like 12 is the best we can do :\ – Shaggy – 2019-04-07T22:26:09.290

I stand corrected! – Shaggy – 2019-04-09T10:49:48.427

2

TI-BASIC (TI-84), 34 bytes

[[0,1,0][0,0,1][1,1,0]]^(Ans+5:Ans(1,1

0-indexed \$N\$th term of the sequence.

Input is in Ans.
Output is in Ans and is automatically printed out.

I figured that enough time had passed, plus multiple answers had been posted, of which there were many which out-golfed this answer.

Example:

0
               0
prgmCDGFD
               1
9
               9
prgmCDGFD
               9
16
              16
prgmCDGFD
              65

Explanation:

[[0,1,0][0,0,1][1,1,0]]^(Ans+5:Ans(1,1      ;full program (example input: 6)

[[0,1,0][0,0,1][1,1,0]]                     ;generate the following matrix:
                                            ; [0 1 0]
                                            ; [0 0 1]
                                            ; [1 1 0]
                       ^(Ans+5              ;then raise it to the power of: input + 5
                                            ; [4  7 5]
                                            ; [5  9 7]
                                            ; [7 12 9]
                               Ans(1,1      ;get the top-left index and leave it in "Ans"
                                            ;implicitly print Ans

Tau

Posted 2019-04-07T20:21:05.717

Reputation: 1 935

2

Pyth, 16 bytes

L?<b3!b+y-b2y-b3

This defines the function y. Try it here!

Here's a more fun solution, though it's 9 bytes longer; bytes could be shaved though.

+l{sa.pMf.Am&>d2%d2T./QY!

This uses the definition given by David Callan on the OEIS page: "a(n) = number of compositions of n into parts that are odd and >= 3." Try it here! It takes input directly instead of defining a function.

RK.

Posted 2019-04-07T20:21:05.717

Reputation: 497

y-b2y-b3 could maybe be refactored with either bifurcate or L? Though declaring an array of 2 elements is costly. yL-Lb2,3 is longer :( – Ven – 2019-04-08T07:42:29.473

@Ven I was able to replace +y-b2y-b3 with smy-bdhB2 which is the same amount of bytes; hB2 results in the array [2, 3] – RK. – 2019-04-08T15:44:07.030

Well done on hB2. Too bad it's the same byte count. – Ven – 2019-04-08T15:44:46.403

Yeah, though I wonder if there's some way to get rid of the d in the map. – RK. – 2019-04-08T15:52:30.673

2

R + pryr, 38 36 bytes

Zero-indexed recursive function.

f=pryr::f(`if`(n<3,1,f(n-2)+f(n-3)))

Try it online!

Thanks to @Giuseppe for pointing out two obviously needless bytes.

rturnbull

Posted 2019-04-07T20:21:05.717

Reputation: 3 689

2

If you're going to be using pryr, the language should be R + pryr and this can be 36 bytes

– Giuseppe – 2019-04-08T19:34:50.607

@Giuseppe thanks! Updated now. – rturnbull – 2019-04-08T20:35:53.037

2

Java, 41 bytes

Can't use a lambda (runtime error). Port of this Javascript answer

int f(int n){return n<3?1:f(n-2)+f(n-3);}

TIO

Benjamin Urquhart

Posted 2019-04-07T20:21:05.717

Reputation: 1 262

I think you are missing some requirements: Have a look at my modification here.

– Shaq – 2019-04-09T09:43:00.523

Please disregard Shaq's comment: your answer is correct and is the shortest Java answer possible (as of Java 12). – Olivier Grégoire – 2019-04-09T13:59:46.947

Ok then. I'm not sure what I "missed" but ok.

Edit: nvm I read the JS answer. – Benjamin Urquhart – 2019-04-09T18:34:17.053

2

C (clang), 41 33 bytes

a(i){return i<3?1:a(i-2)+a(i-3);}

Try it online!

peterzuger

Posted 2019-04-07T20:21:05.717

Reputation: 73

2Welcome to PPCG :) – Shaggy – 2019-04-09T15:17:48.313

1

C# (Visual C# Interactive Compiler), 34 bytes

int f(int g)=>g<3?1:f(g-2)+f(g-3);

Try it online!

Embodiment of Ignorance

Posted 2019-04-07T20:21:05.717

Reputation: 7 014

1

Japt, 12 9 bytes

Returns the nth term, 1-indexed.

@1gZÔä+}g

Try it

@1gZÔä+}g     :Implicit input of integer U
        g     :Starting with the array [0,1] do the following U times, pushing the result to the array each time
@             :  Pass the array through the following function as Z
 1g           :    Get the element at 0-based index 1, with wrapping, from the following
   ZÔ         :    Reverse Z
     ä+       :    Get the sums of each consecutive pair of elements
       }      :  End function
              :Implicit output of the last element in the array

Shaggy

Posted 2019-04-07T20:21:05.717

Reputation: 24 623

1

Perl 5, 34 bytes

sub f{"@_"<3||f("@_"-2)+f("@_"-3)}

Try it online!

Xcali

Posted 2019-04-07T20:21:05.717

Reputation: 7 671

1

C++ (gcc), 81 75 74 bytes

-6 bytes to small golfing

-1 byte thanks to @ceilingcat

int a(int n){int a=1,b=1,c=1,d,i=2;for(;i++<n;c=d)d=a+b,a=b,b=c;return c;}

Try it online!

Simple function to compute the values iteratively. No loop occurs for n<3, so the first cases default to the initial 1.

Neil A.

Posted 2019-04-07T20:21:05.717

Reputation: 2 038

@ceilingcat Thanks, updated. – Neil A. – 2019-04-09T23:15:54.593

1

Wolfram Language (Mathematica), 26 bytes

If[#<3,1,#0[#-2]+#0[#-3]]&

Try it online!

attinat

Posted 2019-04-07T20:21:05.717

Reputation: 3 495

1

Pari/GP, 28 bytes

0-indexed.

f(n)=if(n<3,1,f(n-2)+f(n-3))

Try it online!


Pari/GP, 35 bytes

1-indexed.

n->Vec((1+x+O(x^n))/(1-x^2-x^3))[n]

Try it online!

The generating function of the sequence is \$\frac{1+x}{1-x^2-x^3}\$.

alephalpha

Posted 2019-04-07T20:21:05.717

Reputation: 23 988

1

05AB1E, 8 bytes

This implementation of the binomial formula: a(n) = Sum_{k=0..floor(n/2)} binomial(k+1, n-2k) is interestingly the same length as the recursive solution.

;Ý·-āscO

Try it online!

Explanation

;Ý        # push [0 ... floor(input/2)]
  ·       # double each
   -      # subtract each from input
    ā     # push range [1 ... len(list)]
     s    # swap
      c   # choose
       O  # sum

Emigna

Posted 2019-04-07T20:21:05.717

Reputation: 50 798

1

Brain-Flak, 96 bytes

(()()()){({}[()]<{({}[()])<>(())(<>)}{}>)}{}{({}[()]<<>({}<(({}(({}))<>)<>[{}])>)<>({}<>)<>>)}<>

Try it online!

Riley

Posted 2019-04-07T20:21:05.717

Reputation: 11 345

1

Clojure, 46 bytes

(defn f[n](if(< n 3)1(+(f(- n 2))(f(- n 3)))))

Just for completeness sake :)

Try it online!

dpnmn

Posted 2019-04-07T20:21:05.717

Reputation: 11

Welcome to PPCG :) – Shaggy – 2019-04-10T13:07:15.027

0

Gaia, 16 14 12 bytes

7b@⟨ṇ;(++⟩ₓ(

Try it online!

0-based index. Only holds the last 3 values.

7b		| push [1 1 1]
  @		| push input
   ⟨     ⟩ₓ	| do the following that many times (0 times if 0 or less)
    ṇ		| pop the first element and leave the rest below
     ;		| copy from below
      (		| take the first element
       +	| add the two together
	+	| and concatenate to the list. End loop.
	   (	| finally, take the first element

Gaia, 14 bytes

ø@⟨18b+ₔ…Σ¦⟩ₓ<

Try it online!

Returns the first n elements, 1-based index. < could also be E to get just the nth element.

Uses the identity from the OEIS page \$a(n+5)=\sum\limits_{i=1}^n a(i)\$.

This is quite inefficient, as it repeatedly copies the first few lists.

ø		| push empty list
 @⟨	   ⟩ₓ	| do (input) number of times:
   18b		| push [1 0 0 1 0] by converting 18 to bits
      +ₔ	| append cumulative list (initially empty) to end of bits
	…Σ¦	| and calculate the cumulative sums, replacing old cumulative list
	     <	| finally, take the first (input) elements of cumulative sums

Giuseppe

Posted 2019-04-07T20:21:05.717

Reputation: 21 077

0

Groovy, 22 bytes

a->a<3?1:f(a-2)+f(a-1)

Try it online!

Expired Data

Posted 2019-04-07T20:21:05.717

Reputation: 3 129

0

dc, 50 48 bytes

 2+sx3si1d:a[liddddd3-;ar2-;a+r:a1+silx>M]dsMx;ap

It's 1-indexed! Try it online! Previous version!

Golfed off two bytes by only populating the first element in the array.

Probably can be golfed a bit more, but it's tricky because you have to a: seed the initial values, and b: use arrays since dc doesn't let you pick from arbitrary stack positions.

2+sx3si adds two to the user input at top of stack into register x, and starts an increment counter register i at 3. We have to add two because the array is now populated in such a way that it's 3-indexed.

1d:a populates element 1 of array a with a 1. The 50 byte version populated elements 1 and 2 with 1d2:a1:a. The mechanism works with just the single element populated, however, it just takes a little while to get enough 1s in place such as to start the sequence. Even though going from 1d2:a1:a to 1d:a saves 4 bytes, we now have to 2+ our input. Still two bytes saved. Initially, I thought I had to seed the first three elements with 1dd3:a2:a1:a (+4 bytes), but... dc returns a zero for any unassigned array element, and if we start macro M (below) by creating the third element, adding 0 to 1... we're good to go.

Macro M:

liddddd loads register i and makes a bunch of copies of it. We subtract 3 from one of these, get the corresponding element from a and then swap top of stack. Subtract 2, get the corresponding element from a, add the two elements to get our new value, then swap the top of stack. At this point, :a puts our new value into a at position i. 1+si to increment i, and lx>M to keep running M until we hit our target (stored in x). dsMx runs M, and once M has finished running, the stack should be full of leftover i values, the topmost of which is the last one we made. Load the value from a with ;a and print it with p.

brhfl

Posted 2019-04-07T20:21:05.717

Reputation: 1 291

0

C# (.NET Core), 144 bytes, 0-indexed.

using C=System.Console;class A{static void Main(){int i=int.Parse(C.ReadLine());C.Write(p(i));}static int p(int i){return i<3?1:p(i-2)+p(i-3);}}

Try it online!

Quite frankly, this is not my best work ever. But here it is.

Stackstuck

Posted 2019-04-07T20:21:05.717

Reputation: 209

0

CJam, 16 bytes

qi7Yb{((_j\(j+}j

0-indexed, returns nth item
Try it online!

Explanation: It uses a recursive function to add a(n-2) to a(n-3) to find a(n).

qi7Yb{((_j\(j+}j
qi               - reads input as integer
  7Yb            - push an array of [1, 1, 1]. It does this by pushing 7, then 
                   turning it into binary.
     {        }j - define a recursive function to calculate a(n), where the 
                   predefined values for n = 0,1,2 are 1,1,1
      ((         - subtract 2 from n | Stack: n-2
        _        - duplicate | Stack: n-2, n-2
         j       - find a(n-2) | Stack: n-2, a(n-2)
          \      - swap the top two items in the stack | Stack: a(n-2), n-2
           (     - decrement | Stack: a(n-2), n-3
            j    - find a(n-3) | Stack: a(n-2), a(n-3)
             +   - add, finding a(n)
                 - implicit output

In pseudocode:

read input as integer
define padovan_sequence(n):
    return padovan_sequence(n-2) + padovan_sequence(n-3)
print(padovan_sequence(n))

lolad

Posted 2019-04-07T20:21:05.717

Reputation: 754

0

Stax, 7 bytes

ÉKΦΘÄO¢

Run and debug it

recursive

Posted 2019-04-07T20:21:05.717

Reputation: 8 616