Changeset 283bb9f in mainline for common/include/adt/gcdlcm.h


Ignore:
Timestamp:
2025-09-18T13:50:14Z (2 weeks ago)
Author:
Martin Decky <martin@…>
Branches:
master
Children:
32ae27bb
Parents:
f9c4c433
Message:

Improve the GCD/LCM implementations

Use a faster variant of the Euclid's algorithm to compute the greatest
common divisor.

Use a better variant of the least common multiple computation that
implicitly avoids overflows.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • common/include/adt/gcdlcm.h

    rf9c4c433 r283bb9f  
    4242        static inline type name(type a, type b) \
    4343        { \
    44                 if (a == 0) \
    45                         return b; \
    46                  \
    4744                while (b != 0) { \
    48                         if (a > b) \
    49                                 a -= b; \
    50                         else \
    51                                 b -= a; \
     45                        type remainder = a % b; \
     46                        a = b; \
     47                        b = remainder; \
    5248                } \
    5349                 \
     
    5854        static inline type name(type a, type b) \
    5955        { \
    60                 return (a * b) / gcd(a, b); \
     56                return (a / gcd(a, b)) * b; \
    6157        }
    6258
Note: See TracChangeset for help on using the changeset viewer.