bn_mp_lcm.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #include "tommath_private.h"
  2. #ifdef BN_MP_LCM_C
  3. /* LibTomMath, multiple-precision integer library -- Tom St Denis */
  4. /* SPDX-License-Identifier: Unlicense */
  5. /* computes least common multiple as |a*b|/(a, b) */
  6. mp_err mp_lcm(const mp_int *a, const mp_int *b, mp_int *c)
  7. {
  8. mp_err err;
  9. mp_int t1, t2;
  10. if ((err = mp_init_multi(&t1, &t2, NULL)) != MP_OKAY) {
  11. return err;
  12. }
  13. /* t1 = get the GCD of the two inputs */
  14. if ((err = mp_gcd(a, b, &t1)) != MP_OKAY) {
  15. goto LBL_T;
  16. }
  17. /* divide the smallest by the GCD */
  18. if (mp_cmp_mag(a, b) == MP_LT) {
  19. /* store quotient in t2 such that t2 * b is the LCM */
  20. if ((err = mp_div(a, &t1, &t2, NULL)) != MP_OKAY) {
  21. goto LBL_T;
  22. }
  23. err = mp_mul(b, &t2, c);
  24. } else {
  25. /* store quotient in t2 such that t2 * a is the LCM */
  26. if ((err = mp_div(b, &t1, &t2, NULL)) != MP_OKAY) {
  27. goto LBL_T;
  28. }
  29. err = mp_mul(a, &t2, c);
  30. }
  31. /* fix the sign to positive */
  32. c->sign = MP_ZPOS;
  33. LBL_T:
  34. mp_clear_multi(&t1, &t2, NULL);
  35. return err;
  36. }
  37. #endif