Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream> // cout
- #include <cmath> // sqrt
- #include <chrono> // steady_clock
- #include <sstream> // istringstream
- std::pair<int64_t, double> fib1(int64_t n) {
- auto t1 = std::chrono::steady_clock::now();
- int64_t nth_fib = (1 / std::sqrt(5)) *
- std::pow((1 + std::sqrt(5)) / 2, n) -
- (1 / std::sqrt(5)) *
- std::pow((1 - std::sqrt(5)) / 2, n);
- auto t2 = std::chrono::steady_clock::now();
- double seconds = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1).count();
- return {nth_fib, seconds};
- }
- std::pair<int64_t, double> fib2(int64_t n) {
- auto t1 = std::chrono::steady_clock::now();
- int64_t a = 0, b = 1, c = 1;
- for(int64_t i = 1; i < n; i++) {
- c = a + b;
- a = b;
- b = c;
- }
- auto t2 = std::chrono::steady_clock::now();
- double seconds = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1).count();
- return {c, seconds};
- }
- int main(int argc, const char * argv[]) {
- if(argc == 1) {
- std::cout << "Please specify a valid number to test." << "\n";
- return 1;
- }
- int64_t n;
- if (!(std::istringstream(argv[1]) >> n)) {
- std::cout << "Please specify a valid number to test." << "\n";
- return 1;
- }
- int64_t nth_fib1, nth_fib2;
- double seconds1, seconds2;
- std::tie(nth_fib1, seconds1) = fib1(n);
- std::tie(nth_fib2, seconds2) = fib2(n);
- std::cout << std::fixed << "Method 1: " << nth_fib1 << ", took " << seconds1 << "s\n";
- std::cout << std::fixed << "Method 2: " << nth_fib2 << ", took " << seconds2 << "s\n";
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment