c++c++20sieve-of-eratosthenes

Why doesn't my Sieve of Eratosthenes c++ implementation print anything when sieving above 46349


I'm trying to make a Sieve of Eratosthenes using C++, however, my program, whenever a number 46350 or higher is input as the top end of the sieve range it simply outputs nothing. It seems to, for any lower number work exactly as intended.

My code:

#include <stdio.h>
#include <array>
#include <iostream>
#define squarert 46350 // I found that it doesn't give correct answers if the "squareroot" number is actually the square root of the second number.
#define num squarert
#define size 10001
std::array < long long, size > eSieve ()
{
    std::array < long long, size > primes;    //array declared
    std::array < bool, num > numbers;
    for(int i = 2; i < squarert; i++) {
        numbers[i] = true;
    }
    for(int i = 2; i <= squarert; i++) {
        if (numbers[i]) {
            for(int j = i * i; j < num; j += i) {
                numbers[j] = false;
            }
        }
    }
    int count = 1;
    for(int i = 2; i < num; i++) {
        if(numbers[i]) {
            primes[count] = i;
            count++;
        }
    }
    
  return primes;        //array returned
}

int
main ()
{
    std::array<long long,size> arr;
    
    arr=eSieve(); //function call
    for(int i = 1; i < 10000; i++) {
        std::cout<<arr[i]<<" ";
    }
    return 0;
}

I realize that this is incredibly janky, I was just trying to get a working sieve and then improve the readability.

I tried trial and error to find the exact number at which the program broke, which is 46350. At that number or higher it just completes with exit code 0 and has no output in the console. I can't find anything online related to this number, and it doesn't seem to be anything special in binary. I'm using C++ 20 on onlinegdb.


Solution

  • It turns out I just had an integer overflow error and had to change variable j to a long long.