The last blog introduced how to compile MPIR, and this one talks about how to use it in the program. I mainly use C++ Qt to develop programs, so I only talk about how to apply MPIR in Qt programs.
Here I take the compiled version of mpir_gc as an example, first create a directory: dll_mpir_gc_vc14_win32
and then copy all the required files to this directory, including:
- mpir.h
- mpirxx.h
- mpir_gc_vc14_win32.dll
- mpir_gc_vc14_win32.exp
- mpir_gc_vc14_win32.ilk
- mpir_gc_vc14_win32.lib
- mpir_gc_vc14_win32.pdb
Then create a new text file named: mpir_gc_vc14_win32.pri
Add the following lines to it:
win32: LIBS += -L$$PWD/ -lmpir_gc_vc14_win32
INCLUDEPATH += $$PWD/
DEPENDPATH += $$PWD/
Then add this line to the pro file of our project:
include (./dll_mpir_gc_vc14_win32/mpir_gc_vc14_win32.pri)
The following is a test code, how to compile and run normally shows that everything is set up successfully.
#include <QCoreApplication>
#include <stdio.h>
#include <iostream>
#include <mpir.h>
#include <mpirxx.h>
using std::cout;
using std::endl;
void mpz_test() //计算 100 的阶乘
{
mpz_t integ, long_i;
mpz_init (integ);
mpz_init (long_i);
mpz_set_sx(integ, 1);
for(int i = 2; i<= 100; i++)
{
mpz_set_sx(long_i, i);
mpz_mul(integ, integ, long_i);
}
mpz_out_str(stdout, 10, integ);
}
void mpzxx_test() //计算 100 的阶乘
{
mpz_class sum(1);
for(int i = 2; i<= 100; i++)
{
sum *= i;
}
cout << sum << endl;
}
void mpf_test()// 计算 E 到 100 位有效数字
{
mpf_set_default_prec(500);
mpf_t sum;
mpf_init (sum);
mpf_set_d(sum, 2.0);
mpf_t long_i;
mpf_init(long_i);
mpf_t fact_1;
mpf_init(fact_1);
mpf_set_d(fact_1, 1);
for(int i = 2; i < 100; i ++)
{
mpf_set_d(long_i, i);
mpf_div(fact_1, fact_1, long_i);
mpf_add(sum, sum, fact_1);
}
mpf_out_str (stdout, 10, 100, sum);
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
mpzxx_test();
mpz_test();
putchar('\n');
mpf_test();
return a.exec();
}