-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgcd.cpp
More file actions
52 lines (50 loc) · 1.03 KB
/
gcd.cpp
File metadata and controls
52 lines (50 loc) · 1.03 KB
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
#include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b)
{
int r;
while (b)
{
r = a % b;
a = b;
b = r;
}
return a;
}
//放弃可读性,进行优化
//但是在10的9次方范围内,差距极小。
int nb_gcd(int a, int b)
{
if (a == b)
return a;
if ((a & 1) == 0 && (b & 1) == 0) //均为偶数,移位
return gcd(a >> 1, b >> 1) << 1;
else if ((a & 1) == 0 && (b & 1) != 0)
{
return gcd(a >> 1, b);
}
else if ((a & 1) != 0 && (b & 1) == 0)
return gcd(a, b >> 1);
else //都是奇数,更相减损
{
int big = a > b ? a : b;
int small = a < b ? a : b;
return gcd(big - small, small);
}
}
int main()
{
srand(time(NULL));
for (int i = 0; i < 100000; i++)
{
int a, b;
a = rand();
b = rand();
if (gcd(a, b) != nb_gcd(a, b))
{
printf("写错了。%d %d\n", a, b);
}
printf("%d %d %d\n", a, b, gcd(a, b));
}
return 0;
}