From 1cb1641abc35fed7143c6d4ec7af8739bc056810 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Sat, 2 May 2020 17:56:19 -0400 Subject: [PATCH] compute arbitrarily large fibonacci number --- others/fibonacci_large.cpp | 51 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 others/fibonacci_large.cpp diff --git a/others/fibonacci_large.cpp b/others/fibonacci_large.cpp new file mode 100644 index 000000000..709268b66 --- /dev/null +++ b/others/fibonacci_large.cpp @@ -0,0 +1,51 @@ +/** + * Computes N^th Fibonacci number given as + * input argument. Uses custom build arbitrary integers library + * to perform additions and other operations. + * + * Took 0.608246 seconds to compute 50,000^th Fibonacci + * number that contains 10450 digits! + **/ + +#include "large_number.h" +#include +#include + +large_number fib(unsigned long long n) +{ + large_number f0(1); + large_number f1(1); + + do + { + large_number f2 = f0 + f1; + f0 = f1; + f1 = f2; + n--; + } while (n > 2); // since we start from 2 + return f1; +} + +int main(int argc, char *argv[]) +{ + unsigned long long N; + if (argc == 2) + N = strtoull(argv[1], NULL, 10); + else + { + std::cout << "Enter N: "; + std::cin >> N; + } + + auto start_time = std::chrono::high_resolution_clock::now(); + large_number result = fib(N); + auto end_time = std::chrono::high_resolution_clock::now(); + std::chrono::duration time_taken = end_time - start_time; + + std::cout + << std::endl + << N << "^th Fibonacci number: " << result << std::endl + << "Number of digits: " << result.num_digits() << std::endl + << "Time taken: " << time_taken.count() << " s" << std::endl; + return 0; +} \ No newline at end of file