Created
December 29, 2017 03:05
-
-
Save 20chan/c1b2169e06a6b5445a0dc2390ecb1d91 to your computer and use it in GitHub Desktop.
Calculating nth Fibonacci number with Generic class
This file contains hidden or 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; | |
| namespace fibonacci_test | |
| { | |
| class Program | |
| { | |
| static int Fib(int n) | |
| { | |
| if (n <= 1) return 1; | |
| return Fib(n - 2) + Fib(n - 1); | |
| } | |
| static void Main(string[] args) | |
| { | |
| var fib = typeof(Fibonacci<,>); | |
| var a = typeof(Fib0); | |
| var b = typeof(Fib1); | |
| // Console.WriteLine($"0번째 {new Fib0().Value}"); | |
| // Console.WriteLine($"1번째 {new Fib1().Value}"); | |
| for (int i = 2; i <= 20; i++) | |
| { | |
| var fib_i = fib.MakeGenericType(a, b); | |
| a = b; | |
| b = fib_i; | |
| // dynamic instance = Activator.CreateInstance(fib_i); | |
| // Console.WriteLine($"{i}번째 {instance.Value}"); | |
| } | |
| dynamic fib20 = Activator.CreateInstance(b); | |
| var prev = DateTime.Now; | |
| int val = fib20.Value; | |
| var now = DateTime.Now; | |
| Console.WriteLine($"제너릭 방식으로 : {(now - prev).TotalMilliseconds} ms 걸림"); | |
| prev = DateTime.Now; | |
| Fib(20); | |
| now = DateTime.Now; | |
| Console.WriteLine($"재귀함수 방식으로: {(now - prev).TotalMilliseconds} ms 걸림"); | |
| } | |
| } | |
| class Fibonacci { public Fibonacci() { } } | |
| class Fibonacci<P2, P1> : Fibonacci where P1 : new() where P2 : new() | |
| { | |
| public int Value => ((dynamic)new P1()).Value + ((dynamic)new P2()).Value; | |
| } | |
| class Int1 : Fibonacci<Fibonacci, Fibonacci> | |
| { | |
| public new int Value => 1; | |
| } | |
| class Fib0 : Int1 { } | |
| class Fib1 : Int1 { } | |
| class Fib2 : Fibonacci<Fib0, Fib1> { } | |
| class Fib3 : Fibonacci<Fib1, Fib2> { } | |
| class Fib4 : Fibonacci<Fib2, Fib3> { } | |
| class Fib5 : Fibonacci<Fib3, Fib4> { } | |
| class Fib6 : Fibonacci<Fib4, Fib5> { } | |
| class Fib7 : Fibonacci<Fib5, Fib6> { } | |
| class Fib8 : Fibonacci<Fib6, Fib7> { } | |
| class Fib9 : Fibonacci<Fib7, Fib8> { } | |
| class Fib10 : Fibonacci<Fib8, Fib9> { } | |
| } |
This file contains hidden or 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
| 제너릭 방식으로 : 3251.0026 ms 걸림 | |
| 재귀함수 방식으로: 0.498 ms 걸림 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment