-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathgcd.c
48 lines (39 loc) · 849 Bytes
/
gcd.c
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
/**
* gcd.c
*
* @author Wang Guibao (https://github.com/wangguibao/)
* @brief Calculates greatest common divisor of two positive integers, using Euclidean Algorithm
* https://en.wikipedia.org/wiki/Euclidean_algorithm
*
*/
#include <stdio.h>
int gcd(int a, int b)
{
int remainder = 0;
if (a == 0 || b == 0) {
return 0;
}
if (a < b) {
return gcd(b, a);
}
remainder = a % b;
while (remainder != 0) {
a = b;
b = remainder;
remainder = a % b;
}
return b;
}
int main()
{
int a = 0;
int b = 0;
fprintf(stdout, "Two integers: ");
scanf("%d %d", &a, &b);
if (a < 0 || b < 0) {
fprintf(stderr, "Negative numbers not acceptable\n");
return -1;
}
fprintf(stdout, "Greatest common divisor is: %u", gcd(a, b));
return 0;
}