[关闭]
@Lin-- 2019-09-21T12:04:25.000000Z 字数 1328 阅读 371

ComSec作业二:EGCD

ComSec


  1. /*
  2. * File : GMP_EGCD.cpp
  3. * Author : Hongpei Lin
  4. * Date : 20190910
  5. * Update : 20190921
  6. * Update comment : function EGCD() retrun a array of mpz_t including r,s,d.
  7. * Purpose : using "GMP" to achieve EGCD algorithm
  8. */
  9. #include <iostream>
  10. #include "gmpxx.h"
  11. using namespace std;
  12. mpz_t * EGCD(mpz_t a, mpz_t b);
  13. int main()
  14. {
  15. mpz_t a, b;
  16. mpz_inits(a, b, NULL);
  17. gmp_printf("please input number a and b\n");
  18. gmp_scanf("%Zd%Zd", a, b);
  19. mpz_t * answer;
  20. answer = EGCD(a, b);
  21. gmp_printf("We get that d=%Zd, r=%Zd, s=%Zd", answer[0], answer[1], answer[2]);
  22. system("pause");
  23. free(answer);
  24. mpz_clears(b, a, NULL);
  25. }
  26. mpz_t * EGCD(mpz_t a, mpz_t b)
  27. {
  28. mpz_t * result;
  29. result = (mpz_t *)malloc(3 * sizeof(mpz_t));
  30. mpz_t r0, r1, s0, s1, q, temp_r0, temp_s0, mul, mod, d;
  31. mpz_init_set_str(r0, "1", 10);
  32. mpz_init_set_str(r1, "0", 10);
  33. mpz_init_set_str(s0, "0", 10);
  34. mpz_init_set_str(s1, "1", 10);
  35. mpz_inits(q, temp_r0, temp_s0, mul, mod, d, NULL);
  36. while (!(mpz_sgn(b) == 0))
  37. {
  38. //GCD
  39. mpz_tdiv_q(q, a, b);//q=a/b
  40. mpz_tdiv_r(mod, a, b);//b=a%b
  41. mpz_init_set(a, b);//a=b
  42. mpz_init_set(b, mod);
  43. //gmp_printf("a=%Zd,b=%Zd\n", a, b);
  44. mpz_init_set(temp_r0, r0);
  45. mpz_init_set(temp_s0, s0);
  46. mpz_init_set(r0, r1);//r0=r1
  47. mpz_init_set(s0, s1);//s0=s1
  48. //r1=r0-r1*q
  49. mpz_mul(mul, r1, q);
  50. mpz_sub(r1, temp_r0, mul);
  51. //s1=s0-s1*q
  52. mpz_mul(mul, s1, q);
  53. mpz_sub(s1, temp_s0, mul);
  54. }
  55. mpz_init_set(result[0], a);
  56. mpz_init_set(result[1], r0);
  57. mpz_init_set(result[2], s0);
  58. mpz_clears(d, mod, mul, temp_s0, temp_r0, q, s1, s0, r1, r0, NULL);
  59. return result;
  60. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注