Skip to content

Instantly share code, notes, and snippets.

@madebyjeffrey
Created October 9, 2012 20:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madebyjeffrey/3861301 to your computer and use it in GitHub Desktop.
Save madebyjeffrey/3861301 to your computer and use it in GitHub Desktop.
Fibonacci implementations
// C++ 11
#include <iostream>
#include <utility>
#include <string>
long long BinaryFib(long k)
{
if (k == 0 || k == 1) return k;
return BinaryFib(k-1) + BinaryFib(k-2);
}
std::pair<long, long> LinearFib(long k)
{
if (k == 1) return std::make_pair(k, 0);
auto p = LinearFib(k - 1);
return std::make_pair(p.first + p.second, p.first);
}
int main(int argc, char**argv)
{
if (argc != 3)
{
std::cout << "Usage: fib [b|l] n" << std::endl;
return -1;
}
long num = std::stol(argv[2]);
std::cout << "Calculating the fib of " << num << std::endl;
if (*argv[1] == 'b')
{
std::cout << "Binary Fib " << num << " = " << BinaryFib(num) << std::endl;
} else
if (*argv[1] == 'l')
{
auto k = LinearFib(num);
std::cout << "Linear Fib " << num << " = " << k.second << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment