summaryrefslogtreecommitdiff
path: root/gcd.cpp
blob: 659c77a2363e62cf94f2acad02570574c6ae07b3 (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
63
64
65
66
67
68
69
70
71
/*
 * SYNOPSIS:
 *
 * # g++ -o gcd-cpp gcd.cpp
 * # ./gcd-cpp 11 22 33 121
 * # 11
 *
 *
 * To use GNU Multiple Precision Arithmetic Library:
 * 
 * # g++ -o gcd-cpp-gmp -DGMP -lgmpxx -lgmp gcd.cpp
 * # ./gcd-cpp-gmp 1234567890987654321 987654321234567
 * # 63
 *
 */


#include <cstdlib>
#include <iostream>
#include <vector>
#include <sstream>

using namespace std;

#ifdef GMP
    #include <gmpxx.h>
    typedef mpz_class Number;
#else
    typedef unsigned int Number;
#endif // GMP

typedef vector<Number> Numbers;

Number gcd(Number a, Number b)
{
    Number c;
    while (b != 0) {
        c = b;
        b = a % b;
        a = c;
    }
    return a;
}

Number gcd(const Numbers & ns)
{
    Number r = 0;
    for(Numbers::const_iterator n = ns.begin(); n != ns.end(); ++n)
        r = gcd(*n, r);
    return r;
}


int main (int argc, char *argv[])
{
    if (argc > 1) {
        Numbers ns(argc - 1);
        for(int n = 1; n < argc; ++n) {
            stringstream str;
            str << argv[n];
            str >> ns[n-1];
            /* NOTE:
             * For GMP we can just assign: ns[n-1] = argv[n],
             * and sstream is not needed.
             */
        }
        cout << gcd(ns) << endl;
    }
    return EXIT_SUCCESS;
}