bn_mp_gcd.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #include "tommath_private.h"
  2. #ifdef BN_MP_GCD_C
  3. /* LibTomMath, multiple-precision integer library -- Tom St Denis */
  4. /* SPDX-License-Identifier: Unlicense */
  5. /* Greatest Common Divisor using the binary method */
  6. mp_err mp_gcd(const mp_int *a, const mp_int *b, mp_int *c)
  7. {
  8. mp_int u, v;
  9. int k, u_lsb, v_lsb;
  10. mp_err err;
  11. /* either zero than gcd is the largest */
  12. if (MP_IS_ZERO(a)) {
  13. return mp_abs(b, c);
  14. }
  15. if (MP_IS_ZERO(b)) {
  16. return mp_abs(a, c);
  17. }
  18. /* get copies of a and b we can modify */
  19. if ((err = mp_init_copy(&u, a)) != MP_OKAY) {
  20. return err;
  21. }
  22. if ((err = mp_init_copy(&v, b)) != MP_OKAY) {
  23. goto LBL_U;
  24. }
  25. /* must be positive for the remainder of the algorithm */
  26. u.sign = v.sign = MP_ZPOS;
  27. /* B1. Find the common power of two for u and v */
  28. u_lsb = mp_cnt_lsb(&u);
  29. v_lsb = mp_cnt_lsb(&v);
  30. k = MP_MIN(u_lsb, v_lsb);
  31. if (k > 0) {
  32. /* divide the power of two out */
  33. if ((err = mp_div_2d(&u, k, &u, NULL)) != MP_OKAY) {
  34. goto LBL_V;
  35. }
  36. if ((err = mp_div_2d(&v, k, &v, NULL)) != MP_OKAY) {
  37. goto LBL_V;
  38. }
  39. }
  40. /* divide any remaining factors of two out */
  41. if (u_lsb != k) {
  42. if ((err = mp_div_2d(&u, u_lsb - k, &u, NULL)) != MP_OKAY) {
  43. goto LBL_V;
  44. }
  45. }
  46. if (v_lsb != k) {
  47. if ((err = mp_div_2d(&v, v_lsb - k, &v, NULL)) != MP_OKAY) {
  48. goto LBL_V;
  49. }
  50. }
  51. while (!MP_IS_ZERO(&v)) {
  52. /* make sure v is the largest */
  53. if (mp_cmp_mag(&u, &v) == MP_GT) {
  54. /* swap u and v to make sure v is >= u */
  55. mp_exch(&u, &v);
  56. }
  57. /* subtract smallest from largest */
  58. if ((err = s_mp_sub(&v, &u, &v)) != MP_OKAY) {
  59. goto LBL_V;
  60. }
  61. /* Divide out all factors of two */
  62. if ((err = mp_div_2d(&v, mp_cnt_lsb(&v), &v, NULL)) != MP_OKAY) {
  63. goto LBL_V;
  64. }
  65. }
  66. /* multiply by 2**k which we divided out at the beginning */
  67. if ((err = mp_mul_2d(&u, k, c)) != MP_OKAY) {
  68. goto LBL_V;
  69. }
  70. c->sign = MP_ZPOS;
  71. err = MP_OKAY;
  72. LBL_V:
  73. mp_clear(&u);
  74. LBL_U:
  75. mp_clear(&v);
  76. return err;
  77. }
  78. #endif