Created
January 10, 2020 16:28
-
-
Save Arlorean/1f32083e79ff788e731e2657a11e073e to your computer and use it in GitHub Desktop.
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 number = System.Decimal; | |
namespace Fibonacci { | |
class Program { | |
// Recursion | |
static number fibr(number n) { | |
if (n == 0) { return 0; } | |
if (n == 1) { return 1; } | |
return fibr(n - 1) + fibr(n - 2); | |
} | |
// Tail Recursion | |
static number fibtr(number n, number a, number b) { | |
if (n == 0) { return a; } | |
if (n == 1) { return b; } | |
return fibtr(n-1, b, a+b); | |
} | |
// Iteration | |
static number fibi(number n) { | |
if (n == 0) { return 0; } | |
if (n == 1) { return 1; } | |
number a = 0, b = 1; | |
for (var i=2; i <= n; ++i) { | |
var c = a + b; | |
a = b; | |
b = c; | |
} | |
return b; | |
} | |
static void Main(string[] args) { | |
for (var i=0; i < 100; i++) { | |
Console.WriteLine($"fibtr({i}) = {fibtr(i, 0, 1)}, fibi({i}) = {fibi(i)}"); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment