Created
October 9, 2012 20:46
-
-
Save madebyjeffrey/3861301 to your computer and use it in GitHub Desktop.
Fibonacci implementations
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
// 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