-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgcd.c
48 lines (42 loc) · 778 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
#include <stdlib.h>
#include <stdio.h>
static unsigned long
gcd2 (unsigned long a, unsigned long b)
{
unsigned long c;
while (b != 0)
{
c = b;
b = a % b;
a = c;
}
return a;
}
static unsigned long
gcdn (const unsigned long *a, size_t n)
{
unsigned long r;
size_t i;
r = a[0];
for (i = 1; i < n; i++)
r = gcd2 (r, a[i]);
return r;
}
int
main (int argc, char *argv[])
{
unsigned long *a;
size_t i, n;
if (argc > 1)
{
n = (size_t) (argc - 1);
a = (unsigned long *) malloc (n * sizeof (unsigned long));
if (!a)
return EXIT_FAILURE;
for (i = 1; i <= n; i++)
a[i - 1] = strtoul (argv[i], NULL, 10);
printf ("%lu\n", gcdn (a, n));
free (a);
}
return EXIT_SUCCESS;
}