The Pell Numbers
Introduction
The Pell(no, not Bell) Numbers are a simple, Fibonacci-like sequence, defined by the following relation:
$P_n=\begin{cases}0&\mbox{if }n=0;\\1&\mbox{if }n=1;\\2P_{n-1}+P_{n-2}&\mbox{otherwise.}\end{cases}$
They also have a closed form:
$P_n=\frac{\left(1+\sqrt2\right)^n-\left(1-\sqrt2\right)^n}{2\sqrt2}$
And a matrix multiplication based form, for the daring:
$\begin{pmatrix} P_{n+1} & P_n \\ P_n & P_{n-1} \end{pmatrix} = \begin{pmatrix} 2 & 1 \\ 1 & 0 \end{pmatrix}^n.$
Challenge
Your mission, should you choose to accept it, is to do any one of the following:
-
Given $n$, calculate the $n^{th}$ term of the sequence (0 or 1-indexed).
-
Given $n$, calculate the first $n$ elements of the sequence.
-
Output the sequence indefinitely.
Scoring
This is code-golf. Shortest answer in each language wins.
[APL (Dyalog Classic)], 20 18 …
7d ago
[Python 3], 39 bytes …
8d ago
[Haskell], 21 bytes …
9d ago
3 answers
Python 3, 39 bytes
f=lambda x:x if x<2else 2*f(x-1)+f(x-2)
Generic recursive implementation
2 comments
Not sure why short circuiting isn't working here: Try it online!
@Razetime Because when x=0
the condition (x<2and x)
evaluates to 0
, which is falsy, so or
can't short-circuit.
APL (Dyalog Classic), 20 18 17 16 bytes
⊢/,+.×⍣⎕⍨∘.+⍨⌽⍳2
Matrix implementation, requires ⎕IO←0
. Thanks to @Razetime for the idea, -3 bytes by me
APL (Dyalog Classic), 19 18 bytes
{⍵<2:⍵⋄+/∇¨⍵-1,⍳2}
Generic recursive implementation part 2
-1 byte thanks to @Razetime
APL (Dyalog Classic), 26 bytes
{×⍵:⌊0.5+(∇⍵-1)÷1-⍨2*÷2⋄1}
Random fun implementation
APL (Dyalog Classic), 26 bytes
{a←⍳⌈⍵÷2⋄(2*a)+.×⍵!⍨1+2×a}
Random fun implementation 2
8 comments
fun matrix multiplication(20): 4⊃,+.×⍣⎕⍨2 2⍴2 1 1 0
@Razetime i shaved 2 bytes off your fun matrix implementation - its now tied
I think your link is wrong, and the program doesn't seem to work correctly
I got 19 bytes: ⊢/,+.×⍣⎕⍨2-⍨∘.+⍨⌽⍳2
from it
0 comments