Recamán's sequence (A005132) is a mathematical sequence, defined as such:

A(0) = 0
A(n) = A(n-1) - n if A(n-1) - n > 0 and is new, else
A(n) = A(n-1) + n

A pretty LaTex version of the above (might be more readable):

$$A(n) = \begin{cases}0 & \textrm{if } n = 0 \\ A(n-1) - n & \textrm{if } A(n-1) - n \textrm{ is positive and not already in the sequence} \\ % Seems more readable than %A(n-1) - n & \textrm{if } A(n-1) > n \wedge \not\exists m < n: A(m) = A(n-1)-n \\ A(n-1) + n & \textrm{otherwise} \end{cases}$$

The first few terms are 0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11

To clarify, is new means whether the number is already in the sequence.

Given an integer n, via function argument or STDIN, return the first n terms of the Recamán sequence.

This is a code-golf challenge, so shortest code wins.

  • \$\begingroup\$ What does 'is new' mean? \$\endgroup\$
    – Beta Decay
    Sep 11, 2014 at 16:53
  • 1
    \$\begingroup\$ If a number is new, it means it is not yet in the sequence. Just realized I have typed out the sequence wrong, give me a min to correct it. \$\endgroup\$ Sep 11, 2014 at 16:56
  • \$\begingroup\$ Corrected the sequence. \$\endgroup\$ Sep 11, 2014 at 17:06
  • 1
    \$\begingroup\$ Can you add the first values of the sequence? \$\endgroup\$ Sep 11, 2014 at 17:15
  • \$\begingroup\$ Added the first few numbers! (And a link to its OEIS page) \$\endgroup\$ Sep 11, 2014 at 17:50

49 Answers 49


CJam, 34 33 bytes


Try it online.

Example run

$ cjam <(echo '0ali{_W=_I-__0<4$@#)|@I+@?+}fI1>`') <<< 33
[0 1 3 6 2 7 13 20 12 21 11 22 10 23 9 24 8 25 43 62 42 63 41 18 42 17 43 16 44 15 45 14 46]

How it works

0ali                               " Push S := [ 0 ] and read an integer N from STDIN.    ";
    {                      }fI     " For each I in [ 0 ... (N - 1) ]:                     ";
     _W=                           "   X := S[-1].                                        ";
        _I-                        "   Y := X - I                                         ";
            _0<                    "   A := (Y < 0)                                       ";
           _   4$@#)               "   B := (Y ∊ S)                                       ";
                     @I+           "   Z := X + I                                         ";
                    |   @?         "   C := (A || B) ? Z : Y                              ";
                          +        "   S += [C]                                           ";
                              1>`  " Push str(S[1:]).                                     ";
  • \$\begingroup\$ What change did you make? \$\endgroup\$ Sep 11, 2014 at 19:55
  • \$\begingroup\$ My first approach prepended negative numbers to the sequence, so I didn't have to explicitly check if A(i) - i > 0. However, I didn't prepend enough numbers for small values of n. Now, I just do exactly what the spec says. \$\endgroup\$
    – Dennis
    Sep 11, 2014 at 19:58
  • \$\begingroup\$ 33 vs. 45. So close and yet so far. :) \$\endgroup\$
    – Ingo Bürk
    Sep 12, 2014 at 21:07
  • \$\begingroup\$ Wow, comment without e# in Cjam... tasty cherry. \$\endgroup\$
    – Chromium
    Jun 21, 2018 at 8:04

Hexagony, 212 bytes


Try it online!

Input: a single, positive integer \$n\$ on stdin.

Output: all terms of Recaman's sequence up to and including \$A(n)\$, separated by spaces (note that this means the program will print a total of \$n + 1\$ terms).




Apologies if this is confusing, but it's my first time with Hexagony, so rest assured that it confuses me too.

Let \$n = 6\$. The instruction pointer (IP) starts out in the NW corner, moving along the black path. ? reads \$n\$ from stdin and stores it in the current memory edge. Next, we copy \$n\$ three times while backing up the memory pointer. We also flip the memory pointer and decrement the edge it points to.


The IP eventually wraps around to the upper left corner again, jumping over \ and looping through the rest of the black path. This loop continues until the current edge is 0, at which point the graph looks like so:


This forms the skeleton of our memory layout. Each vertical edge now stores a value \$i\$ from 0 to 6; later, these same edges will store the terms \$A(i)\$ of the sequence as they are computed. Each vertical edge also has 4 contiguous edges that are used for later computations. Let's explain them now:

  • head is used for several purposes, but never to store anything permanently because it is frequently overwritten by other operations.
  • tail is generally used as a temporary variable, but it remains 0 for the last \$i\$ in the sequence, telling the program when to stop.
  • prev stores the value of \$A(i - 1)\$
  • copy straightforwardly stores a copy of \$i\$ or, later, \$A(i)\$

Once the program is done initializing its memory graph, it branches off the black path and onto the red path near the NE corner. First, ! prints the decimal representation of vertical to stdout. Next, we move the memory pointer to tail and test for zero:


If it is zero, @ terminates the program immediately; otherwise, we move to head and set it to 32 (an ASCII space):



; then prints this space to stdout. Finally, we copy vertical to the next prev:



Now that the memory pointer is on the next term, we copy this term's vertical to its copy before moving to its vertical:



- computes prev - copy, which is really \$A(i - 1) - i\$, and stores it in vertical:


If vertical is not positive, < deflects the IP onto the green path, where + instead computes prev + copy (\$A(i - 1) + i\$) and stores it in vertical:


The IP then wraps around to the SW corner, eventually returning to the beginning of the red path and starting the cycle over again.

However, if vertical is positive, we have to make sure it doesn't already exist in the sequence before printing it. In this case, the < in the SE corner branches to the SE, wrapping around and staying on the red path. First, we copy vertical to head:


This puts the memory pointer in a position so that successive loops can enter at the next | mirror. Next, we copy head to the previous term's tail and move to its head.


- computes vertical - tail (\$A(i - 1) - A(i)\$) and stores it in head. Hexagony treats zero as a negative number, so we have to do some convoluted branching to test if head is exactly zero. All that's necessary to know is that if head is zero, we've found a duplicate term, and the program will branch onto the yellow path. Otherwise, it will return to the red path at the { instruction.

If head is zero, we return to the latest term of the sequence with [, which executes the subroutine along the pink and blue paths, before + computes \$A(i - 1) + i\$) like above. We then return to the red path.

If head is not zero, we check if the current term is zero:


If it is, we call the subroutine and go back to the red path through a convoluted series of mirrors. If it isn't, we move to compare the next term, returning to the aforementioned | mirror.

Images created using Timwi's Hexagony Colorer and Esoteric IDE.

  • 2
    \$\begingroup\$ For what its worth, your image with colored paths seems to show that the curly bracket at the end doesn't do anything, you should be able to remove it and the preceding space for an easy -2. \$\endgroup\$
    – je je
    Apr 28, 2021 at 15:14
  • \$\begingroup\$ @jeje Shoot, you're right. I can't believe I didn't see that! It's been so long that I'm not sure I even have the Hexagony Colorer project for the image, but I might correct it when I get the time. \$\endgroup\$ May 1, 2021 at 4:16
  • \$\begingroup\$ thanks, just nice \$\endgroup\$
    – gildux
    Jan 1 at 21:48

Ruby, 71 70 bytes


A very "word-for-word" implementation of the definition.


Haskell, 74

a§v|a<0||a`elem`r v=v|1<2=0-v

Example usage:

λ> r 20

Python 2, 78 75 73 69 Bytes

Kudos to xnor and flornquake
Now almost 10 bytes shorter than the initial answer

exec"p+=1;k=m[-1]-p;m+=k+2*p*(k*(k>0)in m),;"*input()
print m
  • \$\begingroup\$ You can shorten [k,k+2*p][bool] to k+2*p*(bool). \$\endgroup\$
    – xnor
    Sep 11, 2014 at 19:04
  • \$\begingroup\$ Also, k in m or k<0 can be k*(k>=0)in m since if k<0, the product is 0, which is in m. \$\endgroup\$
    – xnor
    Sep 11, 2014 at 19:22
  • \$\begingroup\$ You can write -1 instead of p-1. Edit: You can also make m a tuple and write m=0, and m+=k+2*p*(k*(k>0)in m),. \$\endgroup\$
    – flornquake
    Sep 12, 2014 at 13:14
  • \$\begingroup\$ You can then change the first line to m=p,=0, and increment p at the start of the loop to save another character. \$\endgroup\$
    – flornquake
    Sep 12, 2014 at 13:23
  • \$\begingroup\$ @flornquake Thank you. I did not know that [-1] returns the last element. I learned something today. \$\endgroup\$
    – Markuz
    Sep 12, 2014 at 15:17

Golfscript (41 45)

Try it online here:



This is for the original 45 bytes solution, but it's still pretty much the same:

(,              # push array [0 .. n-1]
[0]\            # push sequence elements as [0] and reverse stack
{               # foreach element in [0 .. n-1] do:
  :m;           # store current element in m and discard
  .m=           # get the previous sequence element
  m)-:^         # subtract the current index from it and store in ^
  0>            # is that number greater than 0?
  \.^?)!        # is that number new to our sequence?
  @&            # logically and both checks
  {^}           # if true, push ^
  {^m)2*+}      # otherwise, add the index twice and push
  +             # add new element to our sequence
`               # make output pretty

Edit #1: Thanks to Dennis for shaving off 4 bytes.


dc, 46 bytes


Try it online!

This program takes input from an otherwise empty stack and outputs to stdout (newline delimited).

I'm really proud of this one - it's beating everything that isn't a dedicated golfing language, and showcases three of my favorite dc golfing tricks:

  • Stack size used as an index variable
  • Refactoring "if A then B else C" into "unconditionally C, and if A then D" where C and D combine to make B
  • the little-used random access array feature to solve a uniqueness constraint


sn             Stores the input in register n
[z+z+0r:a]sF   Defines the macro F, which: 
    z+z+         adds twice the stack size/index variable
    0r:a         resets the "uniqueness" flag to 0 in the array a
               In context, F is the "D" in my description above, 
               changing A(z-1)-z to A(z-1)+z
0              The main loop starts with the previous sequence member on top of 
               the stack and total stack depth equal to the next index. 
               Pushing a zero accomplishes both of these things.
[              Start of the main loop M
  p               Print the previous sequence member, with newline (no pop)
  z-             Calculate A(z-1)-z
  d1>F           If that's nonpositive, (F)ix it to be A(z-1)+z
  d;a            a is my array of flags to see if we've hit this value before
  0<F            If we have, (F)ix it! (nonzero = flag, since ;a is zero by
                 default, and also zero if we just (F)ixed and therefore 
                 don't care about uniqueness right now)
  ddd            Make one copy to keep and two to eat
  :a             Flag this entry as "used" in the uniqueness array a
  zln!<M         If our "index variable" is n or less, repeat!
]dsMx          End of main loop - store it and execute
  • \$\begingroup\$ that's wild, i had no idea dc even existed \$\endgroup\$
    – don bright
    Dec 31, 2018 at 7:08
  • \$\begingroup\$ really very nice. thanks. \$\endgroup\$
    – gildux
    Jan 1 at 21:50

K (oK), 53 bytes


{$[y>c:#x;o[x,(r;*|x+c)(r in x)|0>r:*|x-c;y];x]}[,0;]

Try it online!


Recursive solution.

{$[y>c:#x;o[x,(r;*|x+c)(r in x)|0>r:*|x-c;y];x]}[,0;] / the solution
{                                              }[,0;] / lambda with first arg set as list containing 0
 $[      ;                                  ; ]       / if[condition;true;false]
       #x                                             / length of x
     c:                                               / save as c
   y>                                                 / y greater than? (ie have we produced enough results?)
                                             x        / return x if we are done
          o[                             ;y]          / recurse with new x and existing y
                                      x-c             / subtract c from x
                                    *|                / reverse first, aka last
                                  r:                  / save result as r
                                0>                    / 0 greater than?
                               |                      / or
                       (      )                       / do together
                        r in x                        / r in x?
              ( ;     )                               / use result to index into this 2-item list
                   x+c                                / add c to x
                 *|                                   / reverse first, aka last 
               r                                      / result
            x,                                        / append to x

JavaScript - 81 80 79 70

Kudos to edc65 for helping me save 9 bytes

f=n=>{for(a=[x=i=0];++i<n;)a[i]=x+=x>i&a.indexOf(x-i)<0?-i:i;return a}
  • \$\begingroup\$ -9 :g=n=>{for(a=[x=i=0];++i<n;)a[i]=x+=x>i&a.indexOf(x-i)<0?-i:i;return a} \$\endgroup\$
    – edc65
    Sep 11, 2014 at 18:48
  • \$\begingroup\$ @edc65 Grazie mille :) \$\endgroup\$ Sep 11, 2014 at 19:22

JavaScript, ES6, 74 69 characters

Run the below code in latest Firefox's Web Console.


Will try to golf it more later.

Example usage:

G(11) -> 0,1,3,6,2,7,13,20,12,21,11

MATLAB, 83 78 Bytes

Save the below as f.m (73 Bytes)

A=0;for i=1:n-1 b=A(i)-i;A(i+1)=b+2*i;if b>0&&~any(A==b) A(i+1)=b;end;end

Run from command window (5 bytes)


If the above is not legal, then it requires 90 bytes.

function A=f(n) 
A=0;for i=1:n-1 b=A(i)-i;A(i+1)=b+2*i;if b>0&&~any(A==b) A(i+1)=b;end;end

R: 96 characters




A = function(s,n,m,i) {

Sample Run:

> An(0,34,1)
[1]   0   1   3   6   2   7  13  20  12  21  11  22  10  23   9  24   8
[18]  25  43  62  42  63  41  18  42  17  43  16  44  15  45  14  46  79

JavaScript, 63 bytes


Try it online


Perl 6, 62 57 bytes

{(0,{$-@+@*2*($!>@||$-@∈@)given @[*-1]}...*)[^$]}


-5 bytes thanks to Jo King

Try it online!

  • \$\begingroup\$ that's amazing... that literally looks like my cat walked across my keyboard. \$\endgroup\$
    – don bright
    Dec 31, 2018 at 7:10

05AB1E, 19 bytes


Try it online!


¾ˆ                    # Initialize the global list with 0
  G                   # for N in [1, input-1] do:
   ¯                  # push the global list
    ¤N-               # subtract N from the last item in the list
       D              # duplicate
        Š             # move the copy down 2 spots on the stack
         D            # duplicate again
          0›          # check if it is positive
            *         # multiply, turning negative results to zero
             å        # is the result already present in the list?
              N·*     # multiply by N*2
                 +    # add to the result
                  ˆ   # add this to the list

J, 36 bytes


Try it online!


Python 2, 65 bytes

exec'a+=[n,-n][a+n in v];print a;n-=1;v+=a,n;'*input()

Try it online!

Avoids negative numbers by adding them to the list of already visited numbers.


Java, 144

int[]f(int n){int[]a=new int[n];a[0]=0;int i,j,k,m;for(i=0;i<n-1;){k=a[i++]-i;m=0;for(j=0;j<i;)if(k==a[j++])m=1;a[i]=m<1&k>0?k:k+2*i;}return a;}

Powershell (103)


Another 'word-for-word' implementation down here as well. Surprisingly readable for PowerShell, too.

Sequence is stored in the array $a, and printed out one term per line.

For $n=20 if we run the statement $a-join"," we get


Lua - 141 135 139 135

function s(n)a,b={1},{[0]=0}for i=1,n do k=b[i-1]-i c=k+i+i if(k>0)and(a[k]==nil)then b[i],a[k]=k,1 else b[i],a[c]=c,1 end end return b end

readable version:

function s(n)
for i=1,n do 
   if (k>0) and (a[k]==nil) then 
return b 

I use 2 tables, the first one is called a and it is built so that a[i]=1 iff i has already appeared in the sequence, nil otherwise, while the second table actually holds the sequence

  • \$\begingroup\$ Your sequence should start with 0, though \$\endgroup\$ Sep 11, 2014 at 18:06
  • 1
    \$\begingroup\$ You're right, I didn't look at the question very carefully and assumed it had the same definition at mathworld (starting with 1), I think that won't cost any more character, I'll test and correct it later, I'm writing from my phone now! \$\endgroup\$
    – user25169
    Sep 11, 2014 at 19:26

Python, 73

def f(x,t=0):
 if x:t=f(x-1);t+=2*x*(t*(t>0)in map(f,range(x)))
 return t

Edit 1: Thanks to @xnor's tips on the other Python answer! (I just realised that both look very similar.)

Edit 2: Thanks again, @xnor.

  • \$\begingroup\$ This gives an infinite loop. You need some sort of control flow so that f(x) doesn't always immediately call f(x-1). \$\endgroup\$
    – xnor
    Sep 11, 2014 at 19:25
  • \$\begingroup\$ @xnor fixed the code. \$\endgroup\$ Sep 11, 2014 at 19:36
  • 2
    \$\begingroup\$ This seems to return the nth term, not the first n terms. \$\endgroup\$
    – Dennis
    Sep 11, 2014 at 19:55
  • \$\begingroup\$ Some minor saves: t=0 can go as an optional parameter to f, and t=t+ can be t+=. \$\endgroup\$
    – xnor
    Sep 11, 2014 at 20:21

Groovy : 122 118 111 chars


m=args[0] as int
(1..m-1).each{n->b=a[n-1];x=b-n;(x>0&!(x in a))?a[n]=x:(a[n]=b+n)}
a.each{print "$it "}


m = args[0] as int
a = [0]
(1..m-1).each { n->
    b = a[n-1]
    x = b-n
    ( x>0 & !(x in a) ) ? a[n] = x : (a[n] = b+n) 
a.each{print "$it "}

Sample Run:

bash$ groovy Rec.groovy 14
0 1 3 6 2 7 13 20 12 21 11 22 10 23

Clojure : 174 chars


(defn f[m a](let[n(count a)b(last a)x(- b n)y(if(and(> x 0)(not(.contains a x)))x(+ b n))](if(= m n)a(f m(conj a y)))))(println(f(read-string(first *command-line-args*))[0]))


(defn f[m a]
  (let [n (count a) 
        b (last a) 
        x (- b n) 
        y (if (and (> x 0) (not (.contains a x))) x (+ b n)) ]
    (if (= m n) a (f m (conj a y))) ) )

(println (f (read-string (first *command-line-args*)) [0]) )

Sample run:

bash$ java -jar clojure-1.6.0.jar rec.clj 14 
[0 1 3 6 2 7 13 20 12 21 11 22 10 23]
  • 1
    \$\begingroup\$ I suggest you not to read from STDIN but instead just take an integer argument to the function :) Also you don't get any benefits from defining y on the let form, you can use the expression directly where the value is needed. \$\endgroup\$
    – NikoNyrh
    Jul 26, 2019 at 11:07

Mathcad, 54 "bytes"

enter image description here

From user perspective, Mathcad is effectively a 2D whiteboard, with expressions evaluated from left-to-right,top-to-bottom. Mathcad does not support a conventional "text" input, but instead makes use of a combination of text and special keys / toolbar / menu items to insert an expression, text, plot or component. For example, type ":" to enter the definition operator (shown on screen as ":=") or "ctl-shft-#" to enter the for loop operator (inclusive of placeholders for the iteration variable, iteration values and one body expression). What you see in the image above is exactly what appears on the user interface and as "typed" in.

For golfing purposes, the "byte" count is the equivalent number of keyboard operations required to enter an expression.

  • \$\begingroup\$ That's all well and good, but what are the actual keystrokes? \$\endgroup\$
    – Jo King
    Jun 18, 2018 at 13:14

PHP, 89 bytes


Try it online!


$f = function ($n) {
    for (; $i < $n; $s[$r[$i++] = $p = $m] = 1) {
        if ($s[$m = $p - $i] | 0 > $m) {
            $m = $p + $i;

    return $r;
  • $r for my result
  • $s for tracking seens
  • $p previous value
  • $m mext value

C (gcc), 116 111 109 bytes


Try it online!


Stax, 19 bytes


Run and debug it

Unpacked, ungolfed, and commented, it looks like this. It keeps the sequence so far on the stack, and remembers A(n - 1) in the X register. The iteration index is used for n. The first time through, it's 0, but in that iteration it generates the 0 without any special cases, so there's no need to adjust for the off-by-1 index.

0X      push 0 to main stack and store it in X register, which will store A(n - 1)
z       push an empty array that will be used to store the sequence
,D      pop input from input stack, execute the rest of the program that many times
  xi-Y  push (x-register - iteration-index) and store it in the Y register
        this is (A(n - 1) - n)
  0>    test if (A(n - 1) - n) is greater than 0 (a)
  ny#   count number of times (A(n - 1) - n) occurs in the sequence so far (b)
  >     test if (a) > (b)
    y   (A(n - 1) - n)
    xi+ A(n - 1) + n
  ?     if/else;  choose between the two values based on the condition
  X     store the result in the X register
  Q     print without popping
  +     append to sequence array

Run and debug this one


Pyth, 31 bytes

  • \$\begingroup\$ Welcome to the site! \$\endgroup\$
    – Wheat Wizard
    Jul 19, 2019 at 17:02
  • \$\begingroup\$ Welcome. Code-only answers are discouraged because they tend to be automatically flagged as low-quality. Add an explanation, and consider adding a link to an online interpreter, like this: tio.run/##K6gsyfj/PyzQVjvSPtK@xs4vNTKjIlI3NdJPG4hBdJRm5P//hoYA \$\endgroup\$
    – mbomb007
    Jul 19, 2019 at 18:32

Pyth, 24 bytes


Try it online!

tu+G-eG_W|g0J-eGH}JGHQ]0   Implicit: Q=eval(input())
 u                   Q     Reduce [0-Q)...
                      ]0   ... with initial value G=[0], next value as H:
              eG             Last value of G (sequence so far)
             -  H            Take H from the above
            J                Store in J
          g0J                0 >= J
                 }JG         Is J in G?
         |                   Logical OR of two previous results
       _W           H        If the above is true, negate H, otherwise leave as positive
    -eG                      Subtract the above from last value in G
  +G                         Append the above to G
                           The result of the reduction is the sequence with an extra leading 0
t                          Remove a leading 0, implicit print

x86 machine code, 29 bytes

00000034: 89 fe 31 c0 99 eb 11 29 d0 78 0a 60 89 f7 89 d1  ..1....).x.`....
00000044: f2 af 61 75 03 8d 04 50 ab 42 e2 eb c3           ..au...P.B...

Commented assembly:

        .intel_syntax noprefix
        .globl recaman
        // input: ECX: n, EDI: u32[n]
        // output: stored to EDI
        // Save the array pointer to ESI
        mov     esi, edi
        // EAX (A(n)) = 0
        xor     eax, eax
        // EDX (n) = 0
        // Store first word
        jmp     .Lstore
        // A(n - 1) - n
        sub     eax, edx
        // if negative, do A(n - 1) + n
        js      .Lneg_or_dup
        // We need to save both EDI and ECX, so we do a lazy PUSHA/POPA.
        // EDI = start of array
        mov     edi, esi
        // ECX = current output length
        mov     ecx, edx
        // Search for A(n - 1) - n
        repnz   scasd
        // restore registers
        // If the zero flag is set, we found a match.
        // If not, go directly to store
        jnz     .Lstore
        // Convert A(n - 1) - n to A(n - 1) + n by adding n * 2
        // EAX = EAX + EDX * 2
        lea     eax, [eax + 2 * edx]
        // Store a u32 to EDI and autoincrement
        // Increment length
        inc     edx
        // Decrement counter and loop if non zero
        loop    .Lloop
        // Return

Try it online!

The input is a pointer to an int32_t array of n elements in edi, with n being in ecx.

The output will be stored into edi.


Your Answer

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

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