Skip to content

Instantly share code, notes, and snippets.

@stefc
Created June 21, 2016 12:29
Show Gist options
  • Save stefc/f60e047b419eeb02265a5f04e14c9034 to your computer and use it in GitHub Desktop.
Save stefc/f60e047b419eeb02265a5f04e14c9034 to your computer and use it in GitHub Desktop.
Functional Fibonacci
public static ulong fib1(int n)
{
ulong a = 0;
ulong b = 1;
for (int i = 0; i < n; i++)
{
ulong temp = a;
a = b;
b = temp + b;
}
return a;
}
public static int fib2(int n)
{
return n > 1 ? fib2(n - 1) + fib2(n - 2) : n;
}
public static Func<int,int> fib3()
{
Func<int, int> fib = null;
fib = n => n <= 1 ? n : fib(n - 1) + fib(n - 2);
return fib;
}
public static Func<int,int> fib4()
{
var t = new Dictionary<int,int>();
Func<int, int> fib = null;
fib = x =>
{
if (t.ContainsKey(x)) return t[x];
if (x <=2) return 1;
var result = fib(x-1) + fib(x-2);
t.Add(x,result);
return result;
};
return fib;
}
public static Func<int,int> fib5()
{
Func<int, int> fib = null;
fib = n => n <= 1 ? n : fib(n - 1) + fib(n - 2);
fib = fib.Memoize();
return fib;
}
public static class Ext
{
public static Func<T, TResult> Memoize<T, TResult>(this Func<T, TResult> func)
{
var t = new Dictionary<T, TResult>();
return n =>
{
TResult r;
if (!t.TryGetValue(n, out r))
{
r = func(n);
t.Add(n, r);
}
return r;
};
}
}
static readonly double sqrt5 = Math.Sqrt(5);
static readonly double p1 = (1 + sqrt5) / 2;
static readonly double p2 = -1 * (p1 - 1);
public static ulong fib6(int n)
{
double n1 = Math.Pow(p1, n);
double n2 = Math.Pow(p2, n);
return (ulong)((n1-n2)/sqrt5);
}
public static ulong fib7(int n)
{
double n1 = 1.0;
double n2 = 1.0;
for (int i=0; i<n; i++) // ist trotzdem Pure da identisch zu Math.Pow ?
{
n1*=p1;
n2*=p2;
}
return (ulong)((n1-n2)/sqrt5);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment