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.