-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgcm.cc
114 lines (97 loc) · 1.47 KB
/
gcm.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <algorithm>
#include <cstddef>
#include <utility>
// Recursive Remainder Lemma:
// If r = segment_remainder (a, 2b), then
//
// segment_remainder (a, b) =
// 1) r if r <= b
// 2) r - b if r > b
size_t
rem (size_t a, size_t b)
{
if (a <= b)
return a;
if (a - b <= b)
return a - b;
a = rem (a, 2 * b);
if (a <= b)
return a;
return a - b;
}
size_t
gcm (size_t a, size_t b)
{
while (a != b)
{
a = rem (a, b);
std::swap (a, b);
}
return a;
}
// If we can use %.
int
gcd (int a, int b)
{
while (b != 0)
{
a = a % b;
std::swap (a, b);
}
return a;
}
// Using the Stein algorithm.
#define BinaryInteger typename
template<BinaryInteger N>
bool even (N n)
{
return !(n & 1);
}
template<BinaryInteger N>
N stein_gcd (N m, N n)
{
if (m < N(0))
m = -m;
if (n < N(0))
n = -n;
if (m == N(0))
return n;
if (n == N(0))
return m;
int d_m = 0;
while (even (m))
{
m >>= 1;
++d_m;
}
int d_n = 0;
while (even (n))
{
n >>= 1;
++d_n;
}
// odd (m) && odd (n)
while (m != n)
{
if (n > m)
std::swap (n, m);
m -= n;
do
m >>= 1;
while (even (m));
}
// m == n
return m << std::min (d_m, d_n);
}
int
main ()
{
if (gcm (45, 6) != 3)
__builtin_abort ();
if (gcd (45, 6) != 3)
__builtin_abort ();
if (stein_gcd (45, 6) != 3)
__builtin_abort ();
if (stein_gcd (196, 42) != 14)
__builtin_abort ();
}