V
V
vlad5355352018-02-10 18:45:45
C++ / C#
vlad535535, 2018-02-10 18:45:45

std::bad_alloc error - C++?

Having trouble switching from Python to C++
What's wrong here?
5a7f138763e3a340469419.png

#include <iostream>
#include <vector>

using namespace std;
long long k;
int ans = 0;
int s[10000000];
int n = 10000000;
vector<long long> v1;
int main() {
    for (int i=2; i*i<=n; i++) {
        if (s[i] == 0) {
            for (int j=i*2; j<=n; j+=i) {
                s[j] = 1;

            }
        }
    }
    v1.reserve(100);
    for (int i=2; i<=n; i++) {
        if(s[i] == 0) {
            v1.push_back(i);
        }
    }

    cin  >> k;
    for (int i=0; i<v1.size();i++) {
        if (k == 1 || ans > 20) break;
        while (k%i == 0) {
            ans++;
            if (ans > 20) break;
        }
    }
    if (ans == 20) {
            cout << "Yes";
    }
    else {
            cout << "No";
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav Makarov, 2018-02-10
@vlad535535

Apparently, you are running through memory - in the first cycle you crawled out of the boundaries of the array s and damaged the internal state of the vector v1, after which it cannot behave adequately.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question