Re: [patch V2] lib: GCD: add binary GCD algorithm

From: Peter Zijlstra
Date: Thu Apr 28 2016 - 03:21:28 EST


On Wed, Apr 27, 2016 at 12:20:33PM -0400, George Spelvin wrote:
> The frequent "if (USE_FFS)" conditions seem to clutter the code.
> Would it be easier to read if the two variants were just separated?
> The function is short enough that the duplication isn't too severe.

Yes please, this is _MUCH_ more readable.

> #if USE_FFS
> /* If __ffs is available, the even/odd algorithm benchmarks slower. */
> unsigned long gcd(unsigned long a, unsigned long b)
> {
> unsigned long r = a | b;
>
> if (!a || !b)
> return r;
>
> b >>= __ffs(b);
>
> for (;;) {
> a >>= __ffs(a);
> if (a == b)
> return a << __ffs(r);
> if (a < b)
> swap(a, b);
> a -= b;
> }
> }
>
> #else /* !USE_FFS */
>
> /* If normalization is done by loops, the even/odd algorithm is a win. */
> unsigned long gcd(unsigned long a, unsigned long b)
> {
> unsigned long r = a | b;
>
> if (!a || !b)
> return r;
>
> r &= -r; /* Isolate lsbit of r */
>
> while (!(b & r))
> b >>= 1;
>
> for (;;) {
> while (!(a & r))
> a >>= 1;
> if (a == b)
> return a;
> if (a < b)
> swap(a, b);
> a -= b;
> a >>= 1;
> if (a & r)
> a += b;
> a >>= 1;
> }
> }
> #endif