forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThreeNPlusOneStepsSequence.cs
52 lines (46 loc) · 1.3 KB
/
ThreeNPlusOneStepsSequence.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
47
48
49
50
51
52
using System.Collections.Generic;
using System.Numerics;
namespace Algorithms.Sequences;
/// <summary>
/// <para>
/// Number of halving and tripling steps to reach 1 in the '3n+1' problem.
/// </para>
/// <para>
/// Wikipedia: https://en.wikipedia.org/wiki/Collatz_conjecture.
/// </para>
/// <para>
/// OEIS: https://oeis.org/A006577.
/// </para>
/// </summary>
public class ThreeNPlusOneStepsSequence : ISequence
{
/// <summary>
/// Gets sequence of number of halving and tripling steps to reach 1 in the '3n+1' problem.
/// </summary>
public IEnumerable<BigInteger> Sequence
{
get
{
BigInteger startingValue = 1;
while (true)
{
BigInteger counter = 0;
BigInteger currentValue = startingValue;
while (currentValue != 1)
{
if (currentValue.IsEven)
{
currentValue /= 2;
}
else
{
currentValue = 3 * currentValue + 1;
}
counter++;
}
yield return counter;
startingValue++;
}
}
}
}