I need to fine the first 10000 prime numbers using six threads and print them in order. How can i improve my solution?
#define N 6
#define S 10000
int a[S] = {0};
int is_prime(int n){
int k;
if(n == 2)
return 1;
for (int i = 2; i<n; i++){
k = n%i;
if(k == 0)
return 0;
}
return 1;
}
void* prime_number(void* arg){
int num = (int *) arg;
for(int i = (S/N)*num; i<(S/N)*(num+1) && i<S; i++){
if(is_prime(i))
a[i] = i;
}
pthread_exit(NULL);
}
int main(int argc, char const *argv[]) {
pthread_t *th;
th = malloc(sizeof(pthread_t)*N);
for(int i = 0; i<N; i++){
pthread_create(&th[i], NULL, prime_number, i);
}
for(int i = 0; i<N; i++){
pthread_join(th[i], NULL);
}
for(int i = 0; i<S; i++){
if(a[i] != 0)
printf("%d ", a[i]);
}
printf("\n");
free(th);
return 0;
}
In my solution I save everything in the a array and then I print it. Is there a better way to calculate if a number is prime and, if so, print it without save it in the array?
I need to print the numbers in order.