Pagini recente » Cod sursa (job #2323371) | Cod sursa (job #2323389) | Cod sursa (job #2932793) | Cod sursa (job #2782726) | Cod sursa (job #3238590)
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define MAX_SIZE 100000
#define THREAD_COUNT 4
// Function to compute the GCD using the Euclidean algorithm
inline int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
// Data structure to pass arguments to threads
typedef struct {
int* numbers;
int start;
int end;
long long* result;
} ThreadData;
// Thread function to count coprime pairs
void* count_coprime_pairs(void* arg) {
ThreadData* data = (ThreadData*)arg;
int* numbers = data->numbers;
int start = data->start;
int end = data->end;
long long local_count = 0;
for (int i = start; i < end - 1; i++) {
for (int j = i + 1; j < end; j++) {
if (gcd(numbers[i], numbers[j]) == 1) {
local_count++;
}
}
}
*(data->result) = local_count;
return NULL;
}
int main() {
FILE*f=fopen("cifra2.in","r");
FILE*g=fopen("cifra2.out","w");
int numbers[MAX_SIZE];
int n;
fscanf(f,"%d", &n);
for (int i = 0; i < n; i++) {
fscanf(f,"%d", &numbers[i]);
}
pthread_t threads[THREAD_COUNT];
ThreadData thread_data[THREAD_COUNT];
long long results[THREAD_COUNT] = {0};
int chunk_size = (n + THREAD_COUNT - 1) / THREAD_COUNT; // Divide workload among threads
// Create threads to process chunks of data
for (int i = 0; i < THREAD_COUNT; i++) {
thread_data[i].numbers = numbers;
thread_data[i].start = i * chunk_size;
thread_data[i].end = (i + 1) * chunk_size < n ? (i + 1) * chunk_size : n;
thread_data[i].result = &results[i];
pthread_create(&threads[i], NULL, count_coprime_pairs, &thread_data[i]);
}
// Wait for all threads to complete
long long total_coprime_count = 0;
for (int i = 0; i < THREAD_COUNT; i++) {
pthread_join(threads[i], NULL);
total_coprime_count += results[i];
}
// Print the result
fprintf(g,"%lld", total_coprime_count);
return 0;
}