Reputation: 689
I am trying to run a program and SOMETIMES I'm getting this error when trying to compile
ld returned 1 exit status
Although, when it compiles (like I said, not always) and trying to put certain input, the program outputs the answer... and then crashes. Is there any way is this possible at all?
Here is my code:
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
int main() {
bool flag;
int n,x[] = {1,-1};
long long int A,cont,mul,acum;
while(cin >> n >> A) {
acum = 0;
vector<long long int> nums(n),nums2;
for(int i=0;i<n;i++) cin >> nums[i];
sort(nums.begin(),nums.end());
for(int i=n-1;i>=0;i--) {
flag = 1;
for(int j=0;j<i and flag;j++) if(nums[i]%nums[j] == 0) flag = 0;
if(flag) nums2.push_back(nums[i]);
}
n = nums2.size();
vector<long long int> mult(n,0);
const long long int num = (1<<n);
for(int i=0;i<num;i++) {
cont = 0, mul = 1;
for(int j=n-1;j>=0;j--) if(i & (1<<j)) cont++, mul *= nums2[j];
mult[cont-1] += A/mul;
}
for(int i=0;i<n;i++) acum += (x[i%2]*mult[i]);
cout << acum << endl;
}
return 0;
}
and this is the input I put when the program crashes:
17 1000
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
Upvotes: 0
Views: 130
Reputation: 19899
If you run your program in a debugger, you'll see that the problem occurs on the line
mult[cont-1] += A/mul;
when cont is 0, which means that you are trying to modify element -1 of the vector.
I can't tell what the algorithm is trying to do, so I can't tell why cont might end up zero.
Overall advice: Learn to use a debugger. It's your friend. :)
Upvotes: 3