The Recamán Sequence
May 10, 2019
I’ve been watching Numberphile again, specifically their episode about the Recamán sequence 0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, … A005132, defined as follows:
The Recamán sequence is an integer sequence R with R0 = 0 and Rn = Rn−1 − n if Rn = Rn−1 − n is positive and not already in the sequence and Rn−1 + n otherwise.
Your task is to write a program that generates the Recamán sequence; use your program to compute R1000000 (the one-million-and-first element). When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Interesting problem. Here is my take using Julia:
function recaman(n::Int64)
R = Array{Int64}(undef, n)
R[1] = 1
end
answer: 2057164
Enjoy your weekend!
In Python.
Here’s a solution in C++.
Example Usage: