2020-04-27

给予多个正整数,然后求它们的最大公约数gcd?



#include <iostream>
#include <vector>
int gcd(std::vector<int>* pivec);

int main(void) {
        std::vector<int> ivec;
        int a;
        while (std::cin >> a)
                ivec.push_back(a);
        for (std::vector<int>::size_type i = 0; i != ivec.size(); ++i)
                std::cout << ivec[i] << std::endl;

        std::cout << gcd(&ivec) << std::endl;

        for (std::vector<int>::size_type i = 0; i != ivec.size(); ++i)
                std::cout << ivec[i] << std::endl;
        return 0;
}

int gcd(std::vector<int>* pivec) {
        int smallest = (*pivec)[0];
        //make sure smallest is the smallest in the vector<int>
        for (std::vector<int>::size_type i = 1; i != pivec->size(); ++i)
                if (smallest > (*pivec)[i])
                        smallest = (*pivec)[i];
        //历遍2~smallest
        int gcd = 1;

        for (int i = 2; i != smallest + 1; ++i) {
                bool flag = 1;

        //只有不跳出来,就说明对于这个ivector当中每一个数都可以被这个i整除,i是我要的
        for (std::vector<int>::iterator iter = pivec->begin(); iter != pivec->end(); ++iter)
                if (*iter % i != 0) {
                        flag = 0;
                        break;
                }

        if (flag == 1) {
                gcd *= i;
                for (std::vector<int>::iterator iter = pivec->begin(); iter != pivec->end(); ++iter)
                        *iter /= i;
                smallest /= i;
                i = 1;
        }
        }
        return gcd;
}


以上的代码其实很烦人。而且将原始输入的vector都给改变了。不划算
但是这种方法有一个好处,能够得到质因数。

还有一个方法,不错,很简单。灵感来源于
https://www.tutorialspoint.com/cplusplus-program-for-gcd-of-more-than-two-or-array-numbers

#include <iostream>
#include <vector>
int gcd(int a, int b);
int ngcd(std::vector<int>* pivec);
int main(void) {
        std::vector<int> ivec;
        int a;
        while (std::cin >> a)
                ivec.push_back(a);
        for (std::vector<int>::size_type i = 0; i != ivec.size(); ++i)
                std::cout << ivec[i] << std::endl;
        std::cout << ngcd(&ivec) << std::endl;
        for (std::vector<int>::size_type i = 0; i != ivec.size(); ++i)
                std::cout << ivec[i] << std::endl;
        return 0;
}
int ngcd(std::vector<int>* pivec) {
        int r = (*pivec)[0];
        for (std::vector<int>::size_type i = 1; i != pivec->size(); ++i)
                r = gcd(r, (*pivec)[i]);
        return         r;
}
int gcd(int a, int b) {
        while (a != b)
                (a < b ? b : a) = std::abs(a - b);
        return a;
}

坏处显而易见,没有质因数。

以上两种方法,一运行,什么都不输入,直接ctrl+d,会segmentation fault。

No comments:

How to Add a Directory to PATH in Linux

 https://linuxize.com/post/how-to-add-directory-to-path-in-linux/ When you type a command on the command line, you’re basically telling the ...