# What is the Fibonacci Rectangular Prism Sequence?

The Fibonacci Rectangular Prism Sequence is a sequence derived from the Fibonacci sequence starting with one. The first 3 numbers of the Fibonacci sequence (starting with one) are 1, 1, and 2, so the first number of the Fibonacci Rectangular Prism Sequence is the square of the diagonal length of a rectangular prism (X in this picture) with the dimensions 1x1x2. The next number of the Fibonacci Rectangular Prism Sequence is the square of the diagonal length of a prism with the dimensions 1x2x3, followed by the square of the diagonal of 2x3x5, and so on. The formula for each number in the series would be A127546: $$a(n)={F_n}^2 + {F_{n+1}}^2 + {F_{n+2}}^2$$ where $$\F_n\$$ is the nth number of the Fibonacci sequence. The convention is that $$\F_0\$$ is 0, and $$\F_1\$$ is 1. (See A000045 for more information about the Fibonacci sequence.)

Write code that takes an index $$\n\$$ and outputs the $$\n\$$'th element of the sequence. It’s , so the shortest code wins!

# Test cases:

0 ==> 2
1 ==> 6
2 ==> 14
3 ==> 38
4 ==> 98
5 ==> 258
6 ==> 674
7 ==> 1766
8 ==> 4622
9 ==> 12102
10 ==> 31682

var QUESTION_ID=214423,OVERRIDE_USER=98932,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.rawh\d,e=String.raw\-?\d+\.?\d*,f=String.raw[^\n<>]*,g=String.raw<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>,h=String.raw[^\n\d<>]*,j=String.raw<[^\n<>]+>;return new RegExp(String.raw<${d}>+String.raw\s*([^\n,]*[^\s,]),.*?+String.raw(${e})+String.raw(?=+String.raw${h}+String.raw(?:(?:${g}|${j})${h})*+String.raw</${d}>+String.raw))}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}}

• By the way, a closed form is $$a(n) = 4\cdot\text{round}\left(\frac{\phi^{2n+2}}{5}\right)-2(-1)^n$$ where $\phi$ is the golden ratio.
– lynn
Oct 30, 2020 at 16:26
• I'll be pedantic and say $F_n^2 + F_{n_1}^2 + F_{n_2}^2$ is not a formula, it's a number. Would you consider writing $a(n) = F_n^2 + F_{n_1}^2 + F_{n_2}^2$ instead?
– Stef
Oct 31, 2020 at 8:56
• @Stef That's probably more clear; I'll do that. Oct 31, 2020 at 11:42

# MathGolf, 6 bytes

This is not really interesting (but it is the shortest answer).

3r+f²Σ

## Explanation

3, range, +, Fibonacci, square, sum.

Try it online!

• Surprisingly readable for a golfing language! Oct 30, 2020 at 15:06
• Ah, I forgot MathGolf had a Fibonacci builtin. Btw, not sure if you're aware, but you can add more than one input-lines and it will run each as a separated program: try it online. Oct 30, 2020 at 23:03

# Python 2, 33 bytes

lambda n:((3-5**.5)/2)**~n//5*4+2

Try it online!

34 bytes

lambda n:(5**.5/2+1.5)**-~n//5*4+2

Try it online!

Outputs floats. Based on the closed form by Lynn, simplified to:

$$f(n) = 4 \left \lfloor{\frac{\phi^{2n+2}}{5}}\right \rfloor + 2.$$

We further convert $$\\phi^{2n+2} = (\phi^2)^{n+1} = (\phi+1)^{n+1}\$$, writing $$\\phi+1\$$ as $$\\frac{\sqrt{5}}{2}+1.5\$$. We could also try writing it out as $$\2.61803398875...\$$ to some precision. The limited precision of floats will cause deviations for large enough outputs for any version of this solution.

44 bytes

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

Try it online!

An alternative recursive formula that gets rid of the $$\(-1)^n\$$ term by recursing one step further back.

$$f(n) = 2f(n-1) + 2f(n-2)-f(n-3)$$

where $$\f(n)=2\$$ for $$\n<1\$$.

44 bytes

f=lambda n:2*(n<1)or 3*f(n-1)-f(n-2)+n%2*4-2

Try it online!

Uses a recursive formula, with base case $$\f(-1)=f(0)=2\$$. Writes n%2*4-2 for -2*(-1)**n.

• Cool! Is there an obvious reason why you can seemingly "replace" the 2(-1)^n term with floor?
– lynn
Oct 31, 2020 at 11:14
• @Lynn I'm not quite sure, but the exponential estimate alternates undershooting and overshooting so rounding alternates up and down, I think because like the Fibonacci formula, the omitted conjugate term $c^n$ where $c$ is negative and has absolute value less than one. And the 2(-1)^n was contributing the opposite alternation ($\frac{1}{2} (-1)^n$ inside the multiplier of 4), so they canceled to flooring which just goes down.
– xnor
Oct 31, 2020 at 19:47

# JavaScript (ES6), 34 bytes

Saved 2 bytes thanks to @user and 3 more bytes thanks to @xnor

The following recursive formula is given for $$\n>3\$$ on OEIS, but it actually works for $$\n>1\$$:

$$a(n) = 3a(n-1)-a(n-2)-2(-1)^n$$

As noticed by xnor, we can also make it work for $$\a(1)\$$ by defining $$\a(-1)=a(0)=2\$$.

f=n=>n<1?2:3*f(n-1)-f(n-2)+n%2*4-2

Try it online!

• I think you can get 37 bytes by doing -1^n in a different way
– user
Oct 30, 2020 at 16:03
• @user Thank you! That 2*(-1)**n was looking terribly wrong indeed. Oct 30, 2020 at 16:29
• Shorter base case: TIO
– xnor
Oct 30, 2020 at 22:23

# 05AB1E, 9 7 bytes

2Ý+ÅfnO

Explanation:

2Ý       # Push list [0,1,2]
+      # Add each to the (implicit) input-integer: [n,n+1,n+2]
Åf    # Get the Fibonacci numbers at those indices: [F(n),F(n+1),F(n+2)]
n   # Square each: [F(n)²,F(n+1)²,F(n+2)²]
O  # Sum them together: F(n)²+F(n+1)²+F(n+2)²
# (after which the result is output implicitly)

For funsies and since I was curious, here are the ports of the approaches used in @Razetime's Husk and @Arnauld's JavaScript answers:

10 bytes:

∞<Åfü3nOIè

11 bytes

₂Sλè3*₂®Nm·Æ

Explanation:

∞            # Push an infinite positive list: [1,2,3,4,5,...]
<           # Decrease each by 1 to let it start at 0: [0,1,2,3,4,...]
Åf         # Get the 0-based Fibonacci number: [0,1,1,2,3,...]
ü3       # Create overlapping triplets: [[0,1,1],[1,1,2],[1,2,3],[2,3,5],[3,5,8],..]
n      # Square each inner value: [[0,1,1],[1,1,4],[1,4,9],[4,9,25],[9,25,64],...]
O     # Sum each: [2,6,14,38,98,...]
Iè   # Index the input-integer into the list
# (after which the result is output implicitly)

λ          # Start a recursive environment
è         # to output the 0-based (implicit) input'th value implicitly afterwards,
₂S           # starting at a(0)=2,a(1)=6
# (₂S: push builtin 26, convert it to a list of digits)
# And we calculate every following a(n) as follows:
#  (implicitly push the value of a(n-1)
3*       #  Multiply it by 3: 3*a(n-1)
₂      #  Push a(n-2)
®     #  Push -1
Nm   #  to the power of the current n: (-1)**n
·  #  Double it: 2*(-1)**n
Æ #  Reduce the three values on the stack by subtracting:
#   3*a(n-1)-a(n-2)-2*(-1)**n

# Husk, 8 bytes

ṁ□↑3↓Θİf

Try it online!

ṁ□↑3↓Θİf
Θİf    # fibonacci sequence starting with zero
↓       # remove first n elements (n = input)
↑3        # get first 3 elements of what's left
ṁ□          # square each of them & sum
• Oh, come ONNNN! Oct 30, 2020 at 13:24

f=2:scanl(+)2f
a n=f!!n^2-2*(-1)^n

Try it online!

Uses the $$\a(n)=4F^2_{n+1}-2(-1)^n\$$ formula.

(0!1!!)
a!b|c<-a+b=a^2+b^2+c^2:b!c

Try it online!

Uses the $$\a(n)=F_n^2+F_{n+1}^2+F_{n+2}^2\$$ formula.

# J, 20 bytes

-3 thanks to FrownyFrog

1#.2^~2&(+/@$,$)&1 1

Try it online!

• 2& f &1 1 Execute f n times with 2 as left argument and 1 1 as right argument.
• +/@$,$ Sum first 2 elements of the list, and prepend it to itself
• 1#.2^~ Square and sum.
• 1#.2^~2&(+/@$,$)&1 1 Nov 1, 2020 at 5:03
• @FrownyFrog that's clever! Thanks.
– xash
Nov 1, 2020 at 9:44

# Husk, 9 bytes

!Ẋoṁ□ėΘİf

Try it online!

1-indexed.

## Explanation

!Ẋoṁ□ėΘİf
İf infinite fibonacci sequence
Θ   prepend a 0
Ẋo       map the following over triplets of values
ė    make list of 3 elements
ṁ□     sum their squares
!         index into this list using input
• Gotcha! Oct 30, 2020 at 13:09

# K (ngn/k), 27 25 bytes

{+/t*t:x({x,+/x}1_)/|2\6}

Try it online!

{                       } \ function with parameter x
2\6  \ 6 to binary -? 1 1 0
|     \ reverse -> 0 1 1
x(         )/      \ repeat the function in () n times
1_        \ drop the first number and
{     }          \ apply this function to the remaining list
+/x           \ sum
x,              \ append to the list
t:                   \ assign to t
t*                     \ square
+/                       \ sum

I managed to shave off 2 bytes after seeing @xash's J solution - please upvote their solution!

• To make this work with other k's that don't support |2\6, 011b can be used instead. Here is a port to oK. Oct 31, 2020 at 16:11
• @coltim Thank you for your port to oK! Oct 31, 2020 at 17:58

# R, 3735 31 bytes

Nothing original, given the previous answers:

(((3+5^.5)/2)^(scan()+1)/5)%/%1*4+2

was 35 bytes, but Guiseppe got rid of four parentheses

((3+5^.5)/2)^(scan()+1)%/%5*4+2

Try it online!

• 35 bytes... Oct 31, 2020 at 10:44
• @DominicvanEssen: darn, I first tried this version and it did not work on Tio...! Oct 31, 2020 at 13:46
• I think you'd accidentally left a f= in the header (probably from a previous version), which can interfere with scan()-based golfs...? Oct 31, 2020 at 13:49
• 31 bytes Oct 31, 2020 at 14:01

# Charcoal, 24 23 bytes

Ｆ²⊞υ²ＦＮ⊞υ⁻⊗Σ…⮌υ²§υ±³Ｉ⊟υ

Try it online! Link is to verbose version of code Uses @xnor's recurrence relation. Explanation:

Ｆ²⊞υ²

ＦＮ

Generate as many additional terms as required.

⊞υ⁻⊗Σ…⮌υ²§υ±³

Push twice the sum of the last two terms minus the previous. (On the first loop, there aren't enough terms, but Charcoal indexes cyclically, so it still finds 2 as desired. I could have just started with 3 terms; it makes no difference.)

Ｉ⊟υ

Output the final term, which is the desired result.

Alternative 23-byte solution generates the Fibonacci series:

⊞υ⁰Ｆ⁺²Ｎ⊞υ⊕↨…υι¹ＩΣＸＥ³⊟υ²

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

⊞υ⁰

Ｆ⁺²Ｎ

Extend the sequence until we have all the necessary terms.

⊞υ⊕↨…υι¹

Each term is one more than the sum of all the terms except the previous. I use base conversion from base 1 to avoid the edge case of the empty list.

ＩΣＸＥ³⊟υ²

Pop the last three terms, square them, and print the sum.

# Jelly, 8 bytes

3Ḷ+µÆḞ²S

Try it online!

I feel like it's possible to save a byte here, but I'm not sure how. (EDIT: Apparently the answer was to use 05AB1E; @Kevin Cruijssen's answer, which was written in parallel with this one, uses the same builtins in the same order but 05AB1E happens to parse it the way we'd want.)

You probably shouldn't upvote this answer; it's just a direct translation of the specification and contains no clever golfing tricks. I was just interested in how long it would come out to in Jelly.

## Explanation

3Ḷ+µÆḞ²S
3Ḷ         [0,1,2]
+        add {the input} to {each elemeent}
µ       (fix for parser ambiguity)
ÆḞ     take the Fibonacci number whose index is {each element}
²    square {each element}
S   sum the resulting list {and output it}
• why community wiki? Oct 30, 2020 at 12:26
• @Razetime ais always does that. He doesn't want any rep for some reason. xD Before he used to delete his account every few weeks. :) Oct 30, 2020 at 12:27
• An alternative 8 byter that avoids the µ issue, but doesn’t save any bytes Oct 31, 2020 at 2:01

# Python 2, 47 bytes

I tried a few other methods, like the recurrence realtion used by Arnauld and the formaula provided by Emeric Deutsch on the OEIS page, but a literal implemention seems to be the shortest.

f=lambda n,a=0,b=1:n+2and(n<2)*b*b+f(n-1,b,a+b)

Try it online!

3ÆMgX+U ²

Try it

# C (gcc), 42 38 bytes

Saved 4 bytes thanks to xnor!!!

f(n){n=n<1?2:3*f(n-1)-f(n-2)+n%2*4-2;}

Try it online!

Uses Arnauld's formula from his JavaScript answer.

• A shorter base case with $f(-1)=f(0)=2$: f(n){n=n<1?2:3*f(n-1)-f(n-2)+n%2*4-2;} TIO
– xnor
Oct 30, 2020 at 22:40
• @xnor Nice one - thanks! :D Oct 30, 2020 at 22:43

╗¤û°œJ–¬▀ôƒìÚ„")

Try it!

# Explained

Unpacked: 2+4*:v(phi^(*2+2)/5

Uses the same closed-form variant @xnor uses.

2
+  Plus
4
*  Times
:v  Floor of
(
phi  The golden ratio
^  Exponentiated by
(
_  Variable ≡ STDIN; implied
*
2
+
2
)
/  Divided by
5
)  Implied

Also for fun:

Try it!

# Explained

Unpacked: v:1[2 2{*3- -2*_1^++v}->+2

Sequence definition, the -l flag returns the last entry

# Scala, 53 bytes

def f(n:Int):Int=if(n>0)3*f(n-1)+n%2*4-2-f(n-2)else 2

Try it online

This one uses the method used in @Arnauld's answer.

# Dotty, 84 bytes

n=>{def f:Stream[Int]=0#::1#::f.zip(f.tail).map(_+_);f.slice(n,n+3).map(x=>x*x).sum}

Try it online

# Retina, 39 bytes

K_¶_
"$+"+L$(_+¶)(_+)
$2$1$& %_$=
_

Try it online! No test suite because of the way the program uses history. Explanation:

K_¶_

Replace the input with the first terms (in unary) of the Fibonacci sequence.

"$+"+ Repeat n times... L$(_+¶)(_+)
$2$1$& ... sum the first two terms and drop terms after the third. %`_$=

Square each term separately.

_

Take the sum and convert to decimal.

# Perl 5, 51 bytes

sub a{my$n=pop;(2)[$n]||3*a($n-1)-a($n-2)+\$n%2*4-2}

Try it online!

Just a translation of Arnaulds Javascript answer.