forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RecamansSequence.cs
46 lines (42 loc) · 1.18 KB
/
RecamansSequence.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System.Collections.Generic;
using System.Numerics;
namespace Algorithms.Sequences;
/// <summary>
/// <para>
/// Recaman's sequence. a(0) = 0; for n > 0, a(n) = a(n-1) - n if nonnegative and not already in the sequence, otherwise a(n) = a(n-1) + n.
/// </para>
/// <para>
/// Wikipedia: https://en.wikipedia.org/wiki/Recam%C3%A1n%27s_sequence.
/// </para>
/// <para>
/// OEIS: https://oeis.org/A005132.
/// </para>
/// </summary>
public class RecamansSequence : ISequence
{
/// <summary>
/// Gets Recaman's sequence.
/// </summary>
public IEnumerable<BigInteger> Sequence
{
get
{
yield return 0;
var elements = new HashSet<BigInteger> { 0 };
var previous = 0;
var i = 1;
while (true)
{
var current = previous - i;
if (current < 0 || elements.Contains(current))
{
current = previous + i;
}
yield return current;
previous = current;
elements.Add(current);
i++;
}
}
}
}