#include <bits/stdc++.h> 
    using namespace std;
  
void SieveOfEratosthenes(int n) 
{ 
 
    bool prime[n+1];
    memset(prime, true, sizeof(prime)); 
  
    for (int p=2; p*p<=n; p++) 
    { 

        if (prime[p] == true) 
        { 

            for (int i=p*p; i<=n; i += p) 
                prime[i] = false; 
        } 
    } 

    int index = 0;
    for (int p=2; p<=n; p++) 
       if (prime[p]) 
       {
        index += 1;
            if(index % 100 == 1)
            {
                cout << index << ". " << p << endl;
                
            }
            
       }
           
} 
   
int main() 
{ 
    
    SieveOfEratosthenes(1000000); //if i add another 0 on this function the code won't run
    return 0; 
} 

I am trying to create a program that prints out all prime numbers in increments of 100, starting from 1. First print out the 1st prime number, then the 101st, then 201st, 301st, and so on until the prime number is less or equal to 10^8. However, I can't do that because the program stops printing the number after some time because of what I assume is the memory limit on the array. Is there any way I could further increase these limits so I can print out more prime numbers up to 10^8?

Example of output:

1. 2
101. 547
201. 1229
301. 1993
401. 2749
501. 3581
601. 4421
701. 5281
801. 6143
901. 7001
1001. 7927
1101. 8837
1201. 9739
1301. 10663
1401. 11677
//..... (and so on until,)
78301. 997219
78401. 998617 // it stops here
1

There are 1 best solutions below

0
On

The logic is just wrong. Instead of using a massive array of bools to flag all numbers in the range (which will run out of memory whenever you try an extremely large range), simply use an array of integers with enough elements to cater for the expected number of primes and store the resulting integers within.

This is best done using a vector e.g. std::vector<unsigned long long>. If you're not using c++11+, you may be looking at using malloc and realloc to grab, reserve and resize your results list.