Created
June 1, 2015 22:34
-
-
Save VegaFromLyra/11b9467b0d93c11c599a to your computer and use it in GitHub Desktop.
Nth fibonacci
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 NthFibonacci | |
{ | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
int n = 4; | |
Console.WriteLine("{0}th fibonacci is {1}, Expected {2}", n, nthFibonacci(n), 3); | |
} | |
// O(n) time | |
// O(1) space | |
static int nthFibonacci(int n) { | |
if (n < 0) { | |
throw new Exception("Invalid input"); | |
} | |
if (n == 0 || n == 1) { | |
return n; | |
} | |
int result = 0; | |
int result1 = 0; | |
int result2 = 1; | |
for(int i = 2; i <= n; i++) { | |
result = result1 + result2; | |
result1 = result2; | |
result2 = result; | |
} | |
return result; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment