bn_mp_lcm.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include <tommath.h>
  2. #ifdef BN_MP_LCM_C
  3. /* LibTomMath, multiple-precision integer library -- Tom St Denis
  4. *
  5. * LibTomMath is a library that provides multiple-precision
  6. * integer arithmetic as well as number theoretic functionality.
  7. *
  8. * The library was designed directly after the MPI library by
  9. * Michael Fromberger but has been written from scratch with
  10. * additional optimizations in place.
  11. *
  12. * The library is free for all purposes without any express
  13. * guarantee it works.
  14. *
  15. * Tom St Denis, tomstdenis@gmail.com, http://math.libtomcrypt.com
  16. */
  17. /* computes least common multiple as |a*b|/(a, b) */
  18. int mp_lcm (mp_int * a, mp_int * b, mp_int * c)
  19. {
  20. int res;
  21. mp_int t1, t2;
  22. if ((res = mp_init_multi (&t1, &t2, NULL)) != MP_OKAY) {
  23. return res;
  24. }
  25. /* t1 = get the GCD of the two inputs */
  26. if ((res = mp_gcd (a, b, &t1)) != MP_OKAY) {
  27. goto LBL_T;
  28. }
  29. /* divide the smallest by the GCD */
  30. if (mp_cmp_mag(a, b) == MP_LT) {
  31. /* store quotient in t2 such that t2 * b is the LCM */
  32. if ((res = mp_div(a, &t1, &t2, NULL)) != MP_OKAY) {
  33. goto LBL_T;
  34. }
  35. res = mp_mul(b, &t2, c);
  36. } else {
  37. /* store quotient in t2 such that t2 * a is the LCM */
  38. if ((res = mp_div(b, &t1, &t2, NULL)) != MP_OKAY) {
  39. goto LBL_T;
  40. }
  41. res = mp_mul(a, &t2, c);
  42. }
  43. /* fix the sign to positive */
  44. c->sign = MP_ZPOS;
  45. LBL_T:
  46. mp_clear_multi (&t1, &t2, NULL);
  47. return res;
  48. }
  49. #endif
  50. /* $Source: /cvs/libtom/libtommath/bn_mp_lcm.c,v $ */
  51. /* $Revision: 1.3 $ */
  52. /* $Date: 2006/03/31 14:18:44 $ */