[关闭]
@Lin-- 2019-09-11T01:57:17.000000Z 字数 2096 阅读 386

ComSec作业一:GMP相关

ComSec


练习使用C++和GMP进行大整数和高精度浮点数运算。

  1. /*
  2. * File : GmpWork_1.cpp
  3. * Author : Hongpei Lin
  4. * Date : 20190910
  5. *
  6. * Purpose : using "GMP" to compute Large Int and High precision Float
  7. */
  8. #include <iostream>
  9. #include "gmpxx.h"
  10. using namespace std;
  11. int main( )
  12. {
  13. //Large Int
  14. mpz_t a, b, add, sub, mul, cdiv_q, cdiv_r, fdiv_q, fdiv_r, pow;//define Large Int
  15. //initialize variable,decimal
  16. mpz_init_set_str(a,"1234568799876543210123456789",10);
  17. mpz_init_set_str(b,"98765432101245789",10);
  18. mpz_inits(add, sub, mul, cdiv_q, cdiv_r, fdiv_q, fdiv_r, pow, NULL);
  19. gmp_printf("a=%Zd,b=%Zd\n", a, b);
  20. //compute
  21. mpz_add(add, a, b);//add function
  22. gmp_printf("Large Int add result %Zd\n", add);
  23. mpz_sub(sub, a, b);//sub function
  24. gmp_printf("Large Int sub result %Zd\n", sub);
  25. mpz_mul(mul, a, b);//mul function
  26. gmp_printf("Large Int mul result %Zd\n", mul);
  27. mpz_cdiv_q(cdiv_q, a, b);//div function,ceil
  28. gmp_printf("Large Int div(ceil) result %Zd\n", cdiv_q);
  29. mpz_cdiv_r(cdiv_r, a, b);//mod function,ceil
  30. gmp_printf("Large Int div(ceil) remainder %Zd\n", cdiv_r);
  31. mpz_fdiv_q(fdiv_q, a, b);//div function,floor
  32. gmp_printf("Large Int div(floor) result %Zd\n", fdiv_q);
  33. mpz_fdiv_q(fdiv_r, a, b);//mod function,floor
  34. gmp_printf("Large Int div(floor) remainder %Zd\n", fdiv_r);
  35. mpz_pow_ui(pow, a, 3);//power function
  36. gmp_printf("Large Int pow result %Zd\n", pow);
  37. //free the variable
  38. mpz_clears(pow, fdiv_r, fdiv_q, cdiv_r, cdiv_q, mul, sub, add, a, b, NULL);
  39. gmp_printf("\n");
  40. //High precision Float
  41. mpf_t d, e, f_add, f_sub, f_mul, f_div, f_sqrt;
  42. int n = 30;
  43. //initialize variable
  44. mpf_init_set_d(d, 3.141592653589793238462643383279);
  45. mpf_init_set_d(e, 0.12356454134546482134564445);
  46. mpf_inits(f_add, f_sub, f_mul, f_div, f_sqrt, NULL);
  47. gmp_printf("d=%.*Ff,e=%.*Ff\n", n, d, n, e);
  48. //compute
  49. mpf_add(f_add, d, e);//add function
  50. gmp_printf("High precision Float Add result %.*Ff\n", n, f_add);
  51. mpf_sub(f_sub, d, e);//sub function
  52. gmp_printf("High precision Float Sub result %.*Ff\n", n, f_sub);
  53. mpf_mul(f_mul, d, e);//mul function
  54. gmp_printf("High precision Float Mul result %.*Ff\n", n, f_mul);
  55. mpf_div(f_div, d, e);//div function
  56. gmp_printf("High precision Float Div result %.*Ff\n", n, f_div);
  57. mpf_sqrt(f_sqrt, d);//div function
  58. gmp_printf("High precision Float Sqrt result %.*Ff\n", n, f_sqrt);
  59. mpf_clears(f_sqrt, f_div, f_mul, f_sub, f_add, e, d, NULL);
  60. system("pause");
  61. return 0;
  62. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注