- Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathRecamansSequence.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
usingSystem.Collections.Generic;
usingSystem.Numerics;
namespaceAlgorithms.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: http://oeis.org/A005132.
/// </para>
/// </summary>
publicclassRecamansSequence:ISequence
{
/// <summary>
/// Gets Recaman's sequence.
/// </summary>
publicIEnumerable<BigInteger>Sequence
{
get
{
yieldreturn0;
varelements=newHashSet<BigInteger>{0};
varprevious=0;
vari=1;
while(true)
{
varcurrent=previous-i;
if(current<0||elements.Contains(current))
{
current=previous+i;
}
yieldreturncurrent;
previous=current;
elements.Add(current);
i++;
}
}
}
}