Skip to content

Instantly share code, notes, and snippets.

@VegaFromLyra
Created June 1, 2015 22:34
Show Gist options
  • Save VegaFromLyra/11b9467b0d93c11c599a to your computer and use it in GitHub Desktop.
Save VegaFromLyra/11b9467b0d93c11c599a to your computer and use it in GitHub Desktop.
Nth fibonacci
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