Quy luật của dãy số Fibonacci: số tiếp theo bằng tổng của 2 số trước, 2 số đầu tiên của dãy số là 0, 1. Ví dụ: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, …
Sử dụng yield trong C# để trả về dãy số Fibonacci
static void Main()
{
foreach(var value in Fibonacci())
{
Console.Write(value + " ");
if(value > 1000)
{
break;
}
}
}
static IEnumerable<int> Fibonacci()
{
int current = 0;
int next = 1;
while(true)
{
yield return current;
int oldCurrent = current;
current = next;
next = next + oldCurrent;
}
}
Kết quả:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
