I am new to cuda and am trying to use it to carry out the Sieve of Eratosthenes. The code works for primes below 1000000. Above it i get an unknown kernal launch error. Now I understand this is because I am trying to launch a grid with too many blocks. However if I set the blocks to 1000 I do not get all the prime numbers. I think there may be an issue with the indexing in the kernal but not sure.
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <iostream>
#include <fstream>
#include <stdio.h>
using namespace std;
__global__ static void Sieve(long * sieve, long sieve_size)
{
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx > 1) {
for (int i = idx+idx; i < sieve_size; i += idx) {
sieve[i] = 1;
}
}
}
int main()
{
long *device_sieve;
long *host_sieve = new long[4000000];
ofstream data("data.csv", ofstream::out);
double sieve_size = 4000000 / sizeof(long);
cudaSetDevice(0);
cudaDeviceSynchronize();
cudaThreadSynchronize();
cudaMalloc((void**)&device_sieve, sizeof(long) * sieve_size);
cudaError_t error1 = cudaGetLastError();
cout << "1" << cudaGetErrorString(error1) << endl;
int block = sqrt(sieve_size);
Sieve << <1, block >> >(device_sieve, sieve_size);
cudaThreadSynchronize();
cudaMemcpy(host_sieve, device_sieve, sizeof(long) * sieve_size, cudaMemcpyDeviceToHost);
cudaError_t error = cudaGetLastError();
cout << "2" << cudaGetErrorString(error) << endl;
cudaFree(device_sieve);
for (int i = 2; i < sieve_size; ++i)
if (host_sieve[i] == 0)
data << i << endl;
getchar();
cout << "DONE" << endl;
return 0;
}