Last active
May 20, 2018 07:16
-
-
Save gushwell/dbbe52bcde0f8ea7ede83b893d562ca5 to your computer and use it in GitHub Desktop.
C#:フィボナッチ数列を列挙する ref: https://qiita.com/gushwell/items/dc3731a6131a3bdba406
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static long Fibo(int n) { | |
if (n == 0) | |
return 0; | |
if (n == 1) | |
return 1; | |
return Fibo(n - 1) + Fibo(n - 2); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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