# Fibonacci triangle

Given an integer n, output the following ASCII art to n rows:

1+1=2
1+2=3
2+3=5
3+5=8
5+8=13


Essentially, the first row is 1+1=2 and the nth row (1-indexed) is $$\f_n + f_{n+1} = f_{n+2}\$$ where $$\f\$$ is the Fibonacci sequence, padded so the numbers line up with the previous row.

You may instead output it infinitely. You may output a list of lines.

This is , shortest wins!

## Testcase

The output for 20 should be:

1+1=2
1+2=3
2+3=5
3+5=8
5+8=13
8+13=21
13+21=34
21+34=55
34+55=89
55+89=144
89+144=233
144+233=377
233+377=610
377+610=987
610+987=1597
987+1597=2584
1597+2584=4181
2584+4181=6765
4181+6765=10946
6765+10946=17711

• How exactly is this a triangle? Mar 5, 2022 at 4:07
• Fibonacci swoosh? Mar 5, 2022 at 6:10
• Is leading whitespace allowed? Mar 5, 2022 at 17:12
• @pxeger Allowed? Seems to be required as I read it... Mar 7, 2022 at 16:39
• @DarrelHoffman I mean constant extra leading whitespace, like this: gist.github.com/pxeger/768a57edc59ce03a673d1d6a943ff0d7 Mar 7, 2022 at 18:12

# Python 2, 67 bytes

Outputs the sequence indefinitely.

a=b=l=1
while 1:print'%*d+%d='%(l,a,b)+a+b;l-=~len(b);a,b=b,a+b


Try it online!

# C (gcc), 71 66 bytes

-5 thanks to Sisyphus

i,j;main(k){for(;;)printf("%*d+%d%n=%d\n",i,j=k-j,k+=j,&i,j+k+k);}


Try it online!

Outputs indefinitely.

• 66 bytes using %n: Try it online! Mar 8, 2022 at 11:47

# Charcoal, 25 bytes

≔Ｅ²¦¹ηＦＮ«Ｉ⌊η+≔⟦⌈ηΣη⟧η⟦⪫η=


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

≔Ｅ²¦¹η


Start with two 1s.

ＦＮ«


Repeat n times.

Ｉ⌊η


Output the first element of the old pair.

+


Output a +.

≔⟦⌈ηΣη⟧η


Replace the pair with the second element and their sum.

⟦⪫η=


Output the new pair joined with = and move the cursor down.

# Pip, 30 bytes

W P[xi::o'+o+:i'=i+o]x.:sX#i+1


Outputs forever. Attempt This Online!

### Explanation

W P[xi::o'+o+:i'=i+o]x.:sX#i+1
i is 0, o is 1, x is "", s is " " (implicit)
[                ]           Put the following in a list:
x                            The indent: x
i::o                        Swap i (the smaller number) with o (the larger number)
and return the new value of i
'+                      Plus sign
o+:i                  Add i to o in-place and return the new value of o
'=                Equals sign
P                             Print the list (concatenating its elements by default)
W                               Loop while the list is truthy (which is always):
#i     Length of i
+1   Plus 1
sX       That many spaces
x.:         Concatenate with x in-place


# Python 3.8 (pre-release), 66 bytes @emanresu A

a=b=l=1
while l:=len(x:=f"{a:>{l}}+{b}=%d")-3:a,b=b,a+b;print(x%b)


Try it online!

### Old Python 3.8 (pre-release), 67 bytes

a=b=l=1
while l:=len(x:=f"{a:>{l}}+{b}"):a,b=b,a+b;print(x+f'={b}')


Try it online!

Based on @dingledooper's Python 2 answer.

• You can save a byte with some cursed formatting :) Mar 5, 2022 at 4:12

# JavaScript (ES8), 79 bytes

f=(n,A=B=1,p)=>n?''.padEnd(p)+A++${B}=${B+=A}
+f(n-1,B-A,(A+"").length-~p):''


Try it online!

### Commented

f = (                   // f is a recursive function taking:
n,                    //   n = input
A = B = 1,            //   A, B = Fibonacci variables
p                     //   p = padding length, initially undefined
) =>                    //
n ?                     // if n is not equal to 0:
''.padEnd(p) +        //   append p spaces (none if p is undefined)
A +                   //   followed by A
+${B}=${B += A}\n + //   followed by "+[B]=[B+A]\n" (A is added to B)
f(                    //   followed by the result of a recursive call:
n - 1,              //     decrement n
B - A,              //     update A to the previous value of B
(A + "")            //     add the length of A coerced to a string + 1
.length - ~p        //     to p
)                     //   end of recursive call
:                       // else:
''                    //   stop the recursion


# SNOBOL4 (CSNOBOL4), 90 87 84 bytes

	N =1
N	N =M + (M =N)
OUTPUT =P =DUPL(' ',X) M '+' N '=' M + N
P @X N '='	:(N)
END


Try it online!

Outputs infinitely, but experiences integer overflow after a short while.

# Jelly, 22 bytes

+2ÆḞ€DżṖ©;⁾+=Ɗ⁶ṁ$®¦F)Y  A full program that accepts an integer and prints the result. Try it online! ### How? +2ÆḞ€DżṖ©;⁾+=Ɗ⁶ṁ$®¦F)Y - Main Link: integer, N
)  - for each V in [1..N]:
ÆḞ€                  -   Fibbonacci of each of [1..V+2]
D                 -   to decimal digits -> [,,,...,Digits(Fib(V+2))]
call this FibDigits
Ṗ               -     pop -> [1..V-1]
©              -       (copy this to the register)
⁾+=          -     ['+', '=']
;             -     concatenate -> [1,2,3,...,V-1,'+','=']
call this Fillers
ż                -   FibDigits zip with Fillers
¦    -   sparse application...
®     -   ...to indices: recall from register -> [1..V-1]
$- ...action: last two links as a monad: ⁶ - space character ṁ - mould like (e.g. [[1,4,4],12] -> [[' ',' ',' '], ' '] F - flatten Y - join with newlines - implicit print  # Vyxal, 19 bytes ÞF3l(:n‛+=Y∑꘍,nhL›+  Try it Online! Outputs infinitely. ÞF3l # Take the infinite list of Fibonacci numbers, and get overlapping groups of 3 ( # Looping over that... Y∑ # Interleave... n # The tuple of three numbers ‛+= # With '+=' : ꘍ # Pad that with the correct amount of spaces, without popping the padding amount , # Print that + # Add to the padding amount (initially 0) nhL› # The length of the first number in the tuple, plus one.  # Vyxalj, 30 bytes ÞFẎ3l⟑‛+=fY∑¥$꘍:\=ḟnḢvL₌t¯-h-£


Try it Online!

A big cursed mess of formatting and registering.

# Retina 0.8.2, 55 bytes


1=1
{.*\+
$.&$*
=
+
\d+.(\d+)
$&=$&$*_$1$*_ :_+$.&


Try it online! Tries to output indefinitely but runs out of memory after about 50 seconds on TIO. Explanation:


1=1


Initialise the buffer with a hypothetical previous line.

{


Repeat indefinitely.

.*\+
$.&$*


Replace up to and including the + with spaces. (This only applies after the first loop.)

=
+


Change the = into a +.

\d+.(\d+)
$&=$&$*_$1$*_  Append the sum of the two values in unary. :_+$.&


Convert the unary to decimal and output the result.

# Python, 117 107 103 99 88 bytes

p="1=1"
while p:=" "*(a:=1+p.find("+"))+eval("f'{%s=}'"%p[a:].replace("=","+")):print(p)

Attempt This Online!

Outputs infinitely.

Can probably be much improved.

• How do you use ":=" in a lambda? Mar 4, 2022 at 21:16
• @Fmbalbuena What do you mean by "how"? It's the same as anywhere else Mar 4, 2022 at 21:19

# 05AB1E, 23 22 bytes

ÌLÅfü3ε„+=.ιJ¯Oú,yнg>ˆ


-1 byte after being inspired by @JonathanAllan's Jelly answer

Outputs the first $$\n\$$ lines.

Try it online.

Or a minor 22 bytes alternative:

ÌLÅfDü3„+=δ.ιJs€g>.¥ú»


Try it online.

And the infinite sequence would be 22 bytes as well:

∞Åfü3vy„+=.ιJ¯Oú,yнg>ˆ


Try it online.

Explanation:

Ì              # Increase the (implicit) input-integer by 2
L             # Pop and push a list in the range [1,input+2]
Åf           # Get the 0-based n'th Fibonacci value for each of these
ü3         # Pop and push all overlapping triplets of this list
ε        # Foreach over the triplets:
#  (implicitly push the current triplet)
„+=.ι   #  Intersperse it with "+" and "=" delimiters
J  #  Join this list together to a string
¯       #  Push the global_array (empty by default)
O      #  Sum it together
,    #  Pop and output this line with trailing newline
y       #  Push the pair again
н      #  Pop and push its first item
g     #  Pop and push its length
>    #  Increase it by 1
ˆ   #  Pop and add it to the global_array

• You might be able to save bytes on the infinite version by porting my Vyxal answer and keeping the padding amount on the stack? Mar 5, 2022 at 21:47
• @emanresuA I'm afraid not. It would be 22 bytes as well. 05AB1E remembers the last value if it needs an argument and the stack is now empty, so I will have to push an explicit 0 at the start (otherwise it will use the infinite overlapping triplets list for the padding). In addition, I need an explicit Duplicate within the loop. That, combined with the 1 byte longer Fibonacci builtin compared to your Vyxal answer, is an alternative infinite 22-byter. Mar 5, 2022 at 22:08

# R, 76 bytes

l=b=1
repeat{cat(sprintf("%*d+%d=%d
",l,T,b,s<-T+b));l=l+nchar(b)+1;T=b;b=s}


Try it online!

Outputs infinitely.

### R, 74 69 bytes

b=1
repeat cat(sprintf("%*d+%d=%d
",F<-F+nchar(+T)+1,T,b,b<-T+(T=b)))


Try it online!

# Retina, 54 bytes

K1+1=2
"$+"+(\d+)=(\d+)$
$&¶$.%* $1+$2=$.(*_$2*
A$ Try it online! No test suite because of the way the program uses history. Explanation: K1+1=2  Replace the input with the first line of the output. "$+"+


Repeat n times.

(\d+)=(\d+)$ Match fₙ=fₙ₊₁ from the previous line. $&¶$.%*$1+$2=$.(*_$2*  Append fₙ+fₙ₊₁= plus their sum, with the correct amount of indent. A$


Since the program started with one line and appended n lines, it now has one line too many, so delete the last line.

# Bash, 139 . . . 104 103 bytes

_()($[a=b=1];for n in seq$1;{ printf "%${s}s";echo -n$a+$b;$[c=a+b,s+=~${#a},a=b,b=c];echo "=$c";})


Try it online!

• Is all that whitespace necessary? Mar 5, 2022 at 5:14
• @emanresuA not sure :) Mar 5, 2022 at 5:14
• Removed Mar 5, 2022 at 5:17

l!s@[a,b,c]|[x,y,z]<-show<$>s=(l++x++'+':y++'=':z):(' '<$' ':x++l)![b,c,b+c]
f=""![1,1,2]


Try it online!

f is a stream of lines.
l!s formats current line and computes next triplet s and leading whitespace l

# CJam, 49 47 45 bytes

liX:Y;{[ST*X_,T)+:T;'+Y:K'=XY+:YN]oK:X;(_}g;


Try it online!

# C (gcc), 102 76 72 bytes

b;s;f(a){for(a=b=1;s=printf("%*d+%d",s,a,b);a=b-a)printf("=%d\n",b+=a);}


Try it online!

Saved a whopping 26 bytes thanks to ceilingcat!!!
Saved 3 bytes thanks to m90!!!

Outputs forever!

• A further improvement
– m90
Mar 6, 2022 at 12:43
• @m90 Nice one - thanks! :D Mar 6, 2022 at 17:07

f(a=1,b=1,n=0)=print(" "^n,"$a+$b=$(a+b) ")f(b,a+b,n-~ndigits(a))  Try it online! prints infinitely. To avoid Int64 overflow, replace a=1 with a=big(1) (+5 bytes) # Python 3, 146 141 bytes print("1+1=2") a=[1,1,2] w=2 while 1:print(" "*w+str(a)+"+"+str(a)+"="+str(a+a));del a;w+=len(str(a))+1;a.append(a+a)  Try it online! # Japt-mR, 23 22 bytes Includes a trailing space on each line of output. "+= "¬ËiMg°UÃvÈùT±XÊÃ¬  Try it "+= "¬ËiMg°UÃvÈùT±XÊÃ¬ :Implicit map of each U in the range [0,input) "+= "¬ : Split "+= " to an array of characters Ë : Map i : Prepend °U : Prefix increment U Mg : Get the Uth Fibonacci number, 0-indexed Ã : End map v : Modify the first element È : By passing it through the following function as X ù : Left pad with spaces to length T± : Increment T (initially 0) by XÊ : Length of X Ã : End modification ¬ : Join :Implicit output joined with newlines  # Scala, 228226 225 bytes Saved 3 bytes thanks to the comment of @ceilingcat Golfed version. Try it online! object Main extends App{def f(n:Int)={def g(a:Int,b:Int,n:Int):List[(Int,Int,Int)]=n match{case 0=>Nil case _=>(a,b,a+b)::g(b,a+b,n-1)};g(1,1,n)};f(20).zipWithIndex.map{case((a,b,c),i)=>(" "*i)+s"$a+$b=$c"}.foreach(println)}


Ungolfed version. Try it online!

object Main extends App {

def formatList(list: List[(Int, Int, Int)]): List[String] = {
list.zipWithIndex.map {
case ((a, b, c), i) => (" " * (2 * i)) + s"$a +$b = \$c"
}
}

def fibonacciSeq(n: Int): List[(Int, Int, Int)] = {
def fibHelper(a: Int, b: Int, n: Int): List[(Int, Int, Int)] = n match {
case 0 => Nil
case _ => (a, b, a + b) :: fibHelper(b, a + b, n - 1)
}
fibHelper(1, 1, n)
}

val formatted = formatList(fibonacciSeq(20))
formatted.foreach(println)
}

• It looks like 20` is hardcoded into this; you must be able to take the value as input, or output infinitely. Jul 1 at 8:33