Programming language is C Show finished code and an example
Programming language is C++. Show finished code and an example of the output on PuTTY when done. Use g++ -std=c++17 to compile the code on PuTTY.
Solution
#include <iostream>
#include <sstream>
#include <gmpxx.h>
#include <vector>
#include <boost/numeric/ublas/matrix.hpp>
typedef boost::numeric::ublas::matrix<mpz_class> matrix;
typedef boost::numeric::ublas::identity_matrix<mpz_class> identity_matrix;
matrix operator^(const matrix& a, int n) {
if(n<=0) return identity_matrix(a.size1(), a.size2());
matrix b(prod(a,a));
return n&1 ? prod(a,b^n>>1) : b^n>>1;
}
mpz_class fib(int x) {
matrix A(2,2);
A(0,0)=A(0,1)=A(1,0)=1; A(1,1)=0;
return x==0 ? 0 : (A^(x-1))(0,0);
}
mpz_class f(int n) {
if(n<0)
return n%2 ? fib(-n) : 0-fib(-n);
else
return fib(n);
}
void fib_print(int n) {
std::cout << n << \"th Fibonacci number is \"
<< f(n).get_str(10) << \'\ \';
}
int main(int argc, char** argv) {
std::vector<std::string> args(argv, argv+argc);
try {
fib_print(stoi(args.at(1)));
} catch (std::exception& ) {
std::cout << \"Usage: \" << args[0] << \" <n>\ \";
}
}


