summaryrefslogtreecommitdiff
path: root/gcd-gmp.c
blob: 3de49de93193490fa3eb40c1c76ae5b5647c82a9 (plain)
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
/* 
 * http://gmplib.org/
 *
 * gcc gcd-gmp.c -o gcd-gmp -lgmp
 *
 */

#include <stdlib.h>
#include <stdio.h>
#include <gmp.h>

void gcd2(mpz_t r, mpz_t a1, mpz_t b1)
{
    mpz_t a, b;
    mpz_init_set(a, a1);
    mpz_init_set(b, b1);
    while (mpz_sgn(b) != 0) {
        mpz_set(r, b);    /* r = b; */
        mpz_mod(b, a, b); /* b = a % b; */
        mpz_set(a, r);    /* a = r; */
    }
    mpz_set(r, a);
}

void gcdn(mpz_t r, mpz_t a[], size_t n)
{
    size_t i;
    mpz_set(r, a[0]);
    for (i = 1; i < n; i++)
        gcd2(r, r, a[i]); /* mpz_gcd ;-) */
}


int main (int argc, char *argv[])
{
    mpz_t *a, g;
    int i, n;

    if (argc > 1) {
        n = argc - 1;
        a = malloc(sizeof(mpz_t) * n);
        if (NULL != a) {
            for (i = 1; i <= n; i++)
                mpz_init_set_str(a[i-1], argv[i], 10);

            mpz_init(g);
            gcdn(g, a, n);
            mpz_out_str(NULL, 10, g);
            printf("\n");

            /* No need actually before exit */
            mpz_clear(g);
            for (i = 1; i <= n; i++)
                mpz_clear(a[i-1]);
            free(a);
            return EXIT_SUCCESS;
        }
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}