forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
VanEcksSequence.cs
44 lines (41 loc) · 1.35 KB
/
VanEcksSequence.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
using System.Collections.Generic;
using System.Numerics;
namespace Algorithms.Sequences
{
/// <summary>
/// <para>
/// Van Eck's sequence. For n >= 1, if there exists an m < n such that a(m) = a(n), take the largest such m and set a(n+1) = n-m; otherwise a(n+1) = 0. Start with a(1)=0.
/// </para>
/// <para>
/// OEIS: http://oeis.org/A181391.
/// </para>
/// </summary>
public class VanEcksSequence : ISequence
{
/// <summary>
/// Gets Van Eck's sequence.
/// </summary>
public IEnumerable<BigInteger> Sequence
{
get
{
yield return 0;
var dictionary = new Dictionary<BigInteger, BigInteger>();
BigInteger previous = 0;
BigInteger currentIndex = 2; // 1-based index
while (true)
{
BigInteger element = 0;
if (dictionary.TryGetValue(previous, out var previousIndex))
{
element = currentIndex - previousIndex;
}
yield return element;
dictionary[previous] = currentIndex;
previous = element;
currentIndex++;
}
}
}
}
}