Question

I need Help PLZ. I can't solving this in C program Given is a C program count_primes.c, which is an array Generates 10000 six-digit random numbers and then determines the number of primes in that...

I need Help PLZ. I can't solving this in C program
Given is a C program count_primes.c, which is an array Generates 10000 six-digit random numbers and then determines the number of primes in that array. It also measures the time that elapses during the calculation and returns it to the console along with the number of primes it finds.

(a) Rewrite the program so that N threads are used to count the primes in the array. Each thread is supposed to check a separate part of the array (eg in case of two threads half each).

The number of threads should be passed as a program argument and not be firmly coded! Here is the maximum possible value for
N up10 be limited.

Note: Use POSIX threads. Include the header <pthread.h>. Also, when calling gcc, you must specify -pthread as an additional option. B .: gcc -o count_primescount_primes.c-g-pthread
(b) Test your program for N = 1,2,4 and 8 threads and graph the results.
Explain briefly what value the runtime is for very large N is expected to converge.
In addition, briefly describe a negative effect that you can get with very large ones N gets.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <sys/time.h> // Include for use time functions
#include <pthread.h> // Include for POSIX threads

/** Return milliseconds elapsed since given time. */
int getElapsedTime(struct timeval startTime)
{
struct timeval stopTime, elapsedTime;
gettimeofday(&stopTime, NULL);
timersub(&stopTime, &startTime, &elapsedTime);
return 1000*elapsedTime.tv_sec + elapsedTime.tv_usec/1000;
}

/** Return true if given number z is a prime number. */
bool isPrime(int z)
{
int t = 2;
int tmax = z / 2;
while (t <= tmax && z % t != 0) {
t++;
}
return t > tmax;
}

/**
* Main program: Check n integer values for primes.
*/
int main(int argc, char* argv[])
{
// Create n random integers in array
int numValues = 10000;
int values[numValues];
for (int i = 0; i < numValues; i++) {
values[i] = rand() % 900000 + 100000;
}

// Get current time for time measurement
struct timeval startTime;
gettimeofday(&startTime, NULL);

// Check array for primes in main thread
// TODO: Distribute this to m threads!
int numPrimes = 0;
for (int i = 0; i < numValues; i++) {
if (isPrime(values[i])) {
numPrimes++;
}
}

// Measure computation time
int msec = getElapsedTime(startTime);

// Display results
printf("Found %d primes in %d values in %d ms\n",
       numPrimes, numValues, msec);

return 0;
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <sys/time.h> // Include for use time functions
#include <pthread.h> // Include for POSIX threads

struct arguments
{
   int * array;
   int num;
   int noPrimes;
};
/** Return milliseconds elapsed since given time. */
int getElapsedTime(struct timeval startTime)
{
struct timeval stopTime, elapsedTime;
gettimeofday(&stopTime, NULL);
timersub(&stopTime, &startTime, &elapsedTime);
return 1000*elapsedTime.tv_sec + elapsedTime.tv_usec/1000;
}

/** Return true if given number z is a prime number. */
bool isPrime(int z)
{
int t = 2;
int tmax = z / 2;
while (t <= tmax && z % t != 0) {
t++;
}
return t > tmax;
}
/** function to find number of primes in given array
*/
void *numOfPrimes(void * args)
{
   struct arguments * arg = (struct arguments *) args;
   int *values=arg->array;
   int numValues=arg->num;
   int numPrimes = 0;
for (int i = 0; i < numValues; i++) {
if (isPrime(values[i])) {
numPrimes++;
   arg->noPrimes=numPrimes;
}
}
}
/**
* Main program: Check n integer values for primes.
*/
int main(int argc, char* argv[])
{
// Create n random integers in array
int numValues = 10000;
int values[numValues];
for (int i = 0; i < numValues; i++) {
values[i] = rand() % 900000 + 100000;
}
// Get current time for time measurement
struct timeval startTime;
gettimeofday(&startTime, NULL);
int N;
printf("enter number of threds you need to add\n");
scanf("%d",&N);
pthread_t thread[N]; //thread array to store N number of threads
struct arguments *args[N];
for(int i=0;i<N;i++){
   args[i]=(struct arguments *)malloc (sizeof (struct arguments));
   args[i]->array=&values[0]+i*N; //divide array into N parts
   args[i]->num=numValues/N;
args[i]->noPrimes=0;   //to store number of primes from each thread
   pthread_create(& thread[i], NULL, numOfPrimes,args[i]);
}  
for(int i=0;i<N;i++)
{
   pthread_join(thread[i],NULL); //wait till all the threds finish their job before main going to terminate them
}
// Measure computation time
int msec = getElapsedTime(startTime);
int numPrimes=0;
for(int i=0;i<N;i++)
{
   numPrimes+=args[i]->noPrimes;
}
// Display results
printf("Found %d primes in %d values in %d ms\n",
numPrimes, numValues, msec);

return 0;
}

Add a comment
Know the answer?
Add Answer to:
I need Help PLZ. I can't solving this in C program Given is a C program count_primes.c, which is an array Generates 10000 six-digit random numbers and then determines the number of primes in that...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • 1. (50 pts) Write a C or C++ program A6p1.c(pp) that accepts one command line argument which is an integer...

    1. (50 pts) Write a C or C++ program A6p1.c(pp) that accepts one command line argument which is an integer n between 2 and 6 inclusive. Generate a string of 60 random upper case English characters and store them somewhere (e.g. in a char array). Use pthread to create n threads to convert the string into a complementary string ('A'<>'Z', 'B'<->'Y', 'C''X', etc). You should divide this conversion task among the n threads as evenly as possible, Print out the...

  • Help with a Parallel and Distributed Programming assignment. In this assignment, you will be expl...

    Help with a Parallel and Distributed Programming assignment. In this assignment, you will be exploring different methods of counting the prime numbers between 1 and N. You will use 8 threads, and each will be given a range in which to count primes. The question is: where do you store your counter? Do you use a local variable? Do you use a global variable? Please use the following function to determine whether an integer number is a prime. // Return...

  • Need help. write a C program stack-ptr.c that implements a stack using a link list. Below...

    Need help. write a C program stack-ptr.c that implements a stack using a link list. Below is a skeleton code to start with.Jjust edit to make thread friendly. examplpe: push(5, &top); push(10, &top); push(15, &top); int value = pop(&top); value = pop(&top); value = pop(&top); this program currently has a race condition. use Pthread mutex locks to fix the race conditions. test you now thread safe stack by creating 200 concurrent threads in main() that push and pop values. -use...

  • Please change this 2 thread program to a 4 thread program. /*compile as "gcc thread.c -pthread"...

    Please change this 2 thread program to a 4 thread program. /*compile as "gcc thread.c -pthread" */ #include <pthread.h> #include <stdio.h> #include <time.h> #define SIZE 100000000 //100 M //#define SIZE 10000 #define NUMBER_OF_TIMES 100 float a[SIZE]; typedef struct {        int start;        int end;        double sum;        int pid;    } range; void *thread_function(void *arg) //define a function that will be executed from //within a thread {    range *incoming = (range *) arg;...

  • c++ please read all question edit the program to test different random sizes of the array and give me the time in a file will be like random size of the array and next to it the time it took for each...

    c++ please read all question edit the program to test different random sizes of the array and give me the time in a file will be like random size of the array and next to it the time it took for each size Im trying to do time analysis for Quick sort but i keep getting time = 0 also i want edit the program to test different random sizes of the array and give me the time in a...

  • Using C, I need help debugging this program. I have a few error messages that I'm...

    Using C, I need help debugging this program. I have a few error messages that I'm not sure how to fix. Here is the code I have: /* * C Program to Print a Linked List in Reverse Order */ #include <stdio.h> #include <stdlib.h> struct node { int num; struct node *next; }; int main() { struct node *p = NULL; struct node_occur *head = NULL; int n; printf("Enter data into the list\n"); create(&p); printf("Displaying the nodes in the list:\n");...

  • My following program has an array which holds 1000 random integers between 1-1000. Now I need...

    My following program has an array which holds 1000 random integers between 1-1000. Now I need help to create an array that holds 10,000 random integer between 1-1000 in my following program. The main goal of this program is time analysis by using bubble sort and binary search algorithms. Please do the following task; 1. Replace the 1000 random integers with 10,000 random integers After change please answer the following question 2. what will be happen, if an array holds...

  • I am getting the Segmentation fault error on the Ubuntu machine but not on macOS. Any...

    I am getting the Segmentation fault error on the Ubuntu machine but not on macOS. Any help would be appreciated. /**** main.c ****/ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #include <pthread.h> #include <string.h> #define WORD_LEN 6 #define TOP 10 char * delim = "\"\'.“”‘’?:;-,—*($%)! \t\n\x0A\r"; struct Word { char word[30]; int freq; }; int threadCount; int fileDescriptor; int fileSize; off_t chunk; struct Word* wordArray; int arrIndex = 0; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;...

  • need help editing or rewriting java code, I have this program running that creates random numbers...

    need help editing or rewriting java code, I have this program running that creates random numbers and finds min, max, median ect. from a group of numbers,array. I need to use a data class and a constructor to run the code instead of how I have it written right now. this is an example of what i'm being asked for. This is my code: import java.util.Random; import java.util.Scanner; public class RandomArray { // method to find the minimum number in...

  • Q2. Consider the following C++ program that declares, allocates and fills in a1D array with random...

    Q2. Consider the following C++ program that declares, allocates and fills in a1D array with random numbers between 0 and 100. The array is sent to a function that finds the indices of all items > 50. A new array is created and the indices are stored inside it. The size of the new arrays MUST BE the same as the number of items > 50. The function returns the new array which is then printed out by main. Here...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT