std::bad_alloc thrown on prime number task

56 Views Asked by At

I am working on a task in which I have to print out all the prime numbers between two given numbers, but which are also palindromes. The program crashes, however, throwing an std::bad_alloc. I have tried fixing this by dynamically allocating my two main arrays on the heap, but this did not fix anything. Can anybody please help me fix this error? Here is my code:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <fstream>

using namespace std;

int mini, maxi;
int *list = new int[10000002];
int *visited = new int[10000002];

bool is_pal(string num)
{
    string num2 = num;
    reverse(num2.begin(), num2.end());
    if (num2 == num)
        return true;
    return false;
}
int main()
{
    visited[4] = 1;
    visited[6] = 1;
    visited[8] = 1;
    visited[9] = 1;
    cin >> mini >> maxi;
    for (int i = mini; i <= maxi; i++)
        list[i] = i;
    for (int i = mini; i <= maxi; i++)
    {
        if (visited[i] == 0)
        {
            for (int j = i * 2; j <= maxi; j += i)
            {
                visited[j] = 1;
                list[j] = -1;
            }
        }
    }
    for (int i = mini; i <= maxi; i++)
        if (visited[i] == 0 && is_pal(to_string(list[i])))
            cout << list[i] << "\n";
    return 0;
}
0

There are 0 best solutions below