blob: 7948ab27f0a48332712f4e46ef2b93cbfc0e1a0e [file] [log] [blame]
Florian Fainellid2829222009-06-17 16:28:38 -07001#include <linux/kernel.h>
2#include <linux/gcd.h>
Paul Gortmaker8bc3bcc2011-11-16 21:29:17 -05003#include <linux/export.h>
Florian Fainellid2829222009-06-17 16:28:38 -07004
Zhaoxiu Zengfff7fb02016-05-20 17:03:57 -07005/*
6 * This implements the binary GCD algorithm. (Often attributed to Stein,
7 * but as Knuth has noted, appears in a first-century Chinese math text.)
8 *
9 * This is faster than the division-based algorithm even on x86, which
10 * has decent hardware division.
11 */
12
Paul Burtond0894402018-11-08 23:44:56 +000013#if !defined(CONFIG_CPU_NO_EFFICIENT_FFS)
Zhaoxiu Zengfff7fb02016-05-20 17:03:57 -070014
15/* If __ffs is available, the even/odd algorithm benchmarks slower. */
Randy Dunlap341e9a32017-09-30 08:43:49 -070016
17/**
18 * gcd - calculate and return the greatest common divisor of 2 unsigned longs
19 * @a: first value
20 * @b: second value
21 */
Florian Fainellid2829222009-06-17 16:28:38 -070022unsigned long gcd(unsigned long a, unsigned long b)
23{
Zhaoxiu Zengfff7fb02016-05-20 17:03:57 -070024 unsigned long r = a | b;
Florian Fainellid2829222009-06-17 16:28:38 -070025
Zhaoxiu Zengfff7fb02016-05-20 17:03:57 -070026 if (!a || !b)
27 return r;
Davidlohr Buesoe9687562012-10-04 17:13:18 -070028
Zhaoxiu Zengfff7fb02016-05-20 17:03:57 -070029 b >>= __ffs(b);
30 if (b == 1)
31 return r & -r;
32
33 for (;;) {
34 a >>= __ffs(a);
35 if (a == 1)
36 return r & -r;
37 if (a == b)
38 return a << __ffs(r);
39
40 if (a < b)
41 swap(a, b);
42 a -= b;
Florian Fainellid2829222009-06-17 16:28:38 -070043 }
Florian Fainellid2829222009-06-17 16:28:38 -070044}
Zhaoxiu Zengfff7fb02016-05-20 17:03:57 -070045
46#else
47
48/* If normalization is done by loops, the even/odd algorithm is a win. */
49unsigned long gcd(unsigned long a, unsigned long b)
50{
51 unsigned long r = a | b;
52
53 if (!a || !b)
54 return r;
55
56 /* Isolate lsbit of r */
57 r &= -r;
58
59 while (!(b & r))
60 b >>= 1;
61 if (b == r)
62 return r;
63
64 for (;;) {
65 while (!(a & r))
66 a >>= 1;
67 if (a == r)
68 return r;
69 if (a == b)
70 return a;
71
72 if (a < b)
73 swap(a, b);
74 a -= b;
75 a >>= 1;
76 if (a & r)
77 a += b;
78 a >>= 1;
79 }
80}
81
82#endif
83
Florian Fainellid2829222009-06-17 16:28:38 -070084EXPORT_SYMBOL_GPL(gcd);