Skip to content

Instantly share code, notes, and snippets.

@gushwell
Last active May 20, 2018 07:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gushwell/dbbe52bcde0f8ea7ede83b893d562ca5 to your computer and use it in GitHub Desktop.
Save gushwell/dbbe52bcde0f8ea7ede83b893d562ca5 to your computer and use it in GitHub Desktop.
C#:フィボナッチ数列を列挙する ref: https://qiita.com/gushwell/items/dc3731a6131a3bdba406
using System;
using System.Collections.Generic;
using System.Linq;
namespace Gushwell.Etude {
class Program {
static void Main(string[] args) {
// f(0)..f(50)までを列挙する
var fibos = Fibonacci.Enumerate()
.Select((Value, Index) => new { Index, Value })
.TakeWhile(x => x.Index <= 50);
foreach (var f in fibos) {
Console.WriteLine($"f({f.Index}) = {f.Value}");
}
}
}
static class Fibonacci {
public static IEnumerable<long> Enumerate() {
yield return 0;
yield return 1;
// 無限に求める オーバーフローは無視
long[] array = new long[] { 0, 1 };
while (true) {
var fibo = array[0] + array[1];
array[0] = array[1];
array[1] = fibo;
yield return fibo;
}
}
}
}
public static long Fibo(int n) {
if (n == 0)
return 0;
if (n == 1)
return 1;
return Fibo(n - 1) + Fibo(n - 2);
}
// f(0)..f(50)までを列挙する
for (int i = 0; i <= 50; i++) {
Console.WriteLine(Fibo(i));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment