Can some one use a C program (not a c++ program) to code prime numbers. The prog
ID: 3691535 • Letter: C
Question
Can some one use a C program (not a c++ program) to code prime numbers. The program should first calculate the prime numbers between 2 and 1,000 inclusive. The program should then use fork to spawn 10 processes that will determine the remaining prime numbers from 1,001 to 1,000,000 inclusive.
One child process should calculate the prime numbers from 1,001 to 100,000 inclusive. Another child process should calculate the prime numbers from 100,001 to 200,000 inclusive. Another child process should calculate the prime numbers from 200,001 to 300,000 inclusive.
Explanation / Answer
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <stdio.h>
#include <sys/wait.h>
#include <stdlib.h>
int DoWorkInChild(int,int);
int main(int argc, char **argv)
{
pid_t pids[10];
int i,n = 10, j = 2,k=1000, count, c;
/* Start children. */
for (i = 0; i < n; ++i)
{
if ((pids[i] = fork()) < 0)
{
perror("fork");
abort();
}
else if (pids[i] == 0)
{
if(i==0)
{
if ( k <= 1 )
{
printf("First %d prime numbers are : ",k);
printf("2 ");
return 0;
}
for ( count = 2 ; count <= k ; j++ )
{
for ( c = 2 ; c <= j - 1 ; c++ )
{
if ( j%c == 0 )
break;
}
if ( c == j )
{
printf(" %d",j);
count++;
}
}
}
j=DoWorkInChild(j,100000);
exit(0);
}
}
/* Wait for children to exit. */
int status;
pid_t pid;
while (n > 0)
{
pid = wait(&status);
printf(" Child with PID %ld exited with status 0x%x. ", (long)pid, status);
--n; // TODO(pts): Remove pid from the pids array.
}
}
int DoWorkInChild(int j,int k)
{
int count,c;
if ( k <= 1 )
{
printf("First %d prime numbers are : ",k);
printf("2 ");
return 0;
}
for ( count = j+1 ; count <= k ; j++ )
{
for ( c = 2 ; c <= j - 1 ; c++ )
{
if ( j%c == 0 )
break;
}
if ( c == j )
{
printf(" %d",j);
count++;
}
}
return j-1;
}