A FibonacciSequenceGenerator in C# looking for speed improvements. Currently generates 1 million numbers in 25.6 seconds.
We must use BigInteger
because the millionth value of the fibonacci sequence is to large to be of type int, long or even ulong. The result is
321,851,935,320,379,656,981,593,474,058,423,769,576,631,910,586,124,350,734,165,842,941,925,697,016,841,709,864,286,954,963,999,053,893,210,468,451,823,262,689,301,306,354,971,797,888,450,164,394,326,059,611,966,197,395,383,319,235,950,480,124,291,916,245,341,634,240,900,324,421,701,713,313,536,116,741,151,743,685,386,112,679,838,085,751,595,026,298,237,888,310,581,559,936,076,376,732,277,717,878,156,239,165,063,784,311,584,934,950,615,070,580,050,766,101,316,621,663,659,924,168,685,017,274,539,048,501,732,419,659,165,366,739,643,571,036,629,605,128,578,575,406,399,390,382,232,885,973,323,204,930,777,394,811,232,955,491,515,525,136,802,939,173,659,827,568,760,916,113,567,628,946,853,363,287,878,329,995,694,272,856,105,316,964,407,030,712,526,846,366,787,342,274,072,376,747,074,044,654,480,541,848,128,317,663,973,778,045,391,111,390,939,319,791,802,953,057,217,582,860,428,225,412,543,991,616,189,585,681,051,405,547,609,150,015,743,785,653,005,260,331,629,522,108,003,916,074,509,262,836,314,172,778,883,659,535,102,587,911,419,872,025,962,380,687,123,573,280,832,406,684,390,626
public readonly struct FibonacciSequenceGenerator(int n) : IEnumerable<BigInteger>
{
public readonly IEnumerator<BigInteger> GetEnumerator()
{
BigInteger a = 0, b = 1, next;
for (BigInteger i = 0; i < n; i++)
{
yield return a;
next = a + b;
a = b;
b = next;
}
}
readonly IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
Changing my GetEnumerator() to the below cuts the time to 12 seconds
public readonly IEnumerator<BigInteger> GetEnumerator()
{
BigInteger a = 0, b = 1, i = 0, next;
for (; i < n; i++)
{
yield return a;
next = a + b;
a = b;
b = next;
}
}
yield a=a+b;yield b=b+a;
approach, with non-conclusive results (~9.7 seconds for both, order varies), and it's JS anyway. But as a by-product I had the actual number and could search for 321851 inside it and when I found it, I just cut the number there by pressing <kbd>Enter</kbd>, and put the comma-separated one below it, then removed the commas. All in mighty Notepad. \$\endgroup\$69
. Because the sequence is infinite, it cannot be ruled out that the lowest 819 digits of two-or-more FibNos are duplicate values. Paraphrasing Richard Feynman, "There's a lot of room at the top." (OP didn't show calling code. Second snippet could involveBigInteger n
... Anything is possible.):-)
\$\endgroup\$