我在代码中遇到分段错误,我想知道为什么。我正在猜测它的vector.erase()
功能。
#include <iostream>
#include <vector>
#include <math.h>
long long gcd(long long x, long long y);
std::vector<long long> factor(long long x);
typedef std::vector<long long> vectorNum;
int main(int argc, const char * argv[])
{
// insert code here...
long long unFriendly;
long long friendly;
long long counter = 0;
std::cin >> unFriendly;
std::cin >> friendly;
vectorNum n;
n = factor(friendly);
for(long long x = 0;x < unFriendly;x++){
long long num = 0;
std::cin >> num;
counter = gcd(friendly, num);
for(long long y = n.size() - 1;y >= 0;y--){
vectorNum temp(n);
if(counter % n.at(y) == 0){
n.erase(n.begin() + y);
}
}
}
std::cout<<n.size();
n.clear();
}
long long gcd(long long x, long long y){
while(y != 0){
long long a = x % y;
x = y;
y = a;
}
return x;
}
std::vector<long long> factor(long long x){
long long y;
long long root = sqrt(x);
std::vector<long long> vectorSet;
for(y = 2; y <= root;y++){
if(x % y == 0){
vectorSet.push_back(y);
vectorSet.push_back(x / y);
}
}
vectorSet.push_back(x);
return vectorSet;
}
任何形式的洞察力都是完美的!提前致谢。这两个函数都被调用。gcd()
和功能都factors()
按要求。