在C語言中,可以使用POSIX線程庫(pthread)來實現多線程因子分解
#include<stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <math.h>
typedef struct {
int number;
int start;
int end;
} FactorData;
void *find_factors(void *arg) {
FactorData *data = (FactorData *)arg;
int number = data->number;
int start = data->start;
int end = data->end;
for (int i = start; i <= end; i++) {
if (number % i == 0) {
printf("Thread %lu: %d is a factor of %d\n", pthread_self(), i, number);
}
}
return NULL;
}
int main() {
int number;
printf("Enter the number to be factorized: ");
scanf("%d", &number);
int num_threads = 4;
pthread_t threads[num_threads];
FactorData data[num_threads];
int range = (int)sqrt(number) / num_threads;
for (int i = 0; i < num_threads; i++) {
data[i].number = number;
data[i].start = i * range + 1;
data[i].end = (i + 1) * range;
pthread_create(&threads[i], NULL, find_factors, (void *)&data[i]);
}
for (int i = 0; i < num_threads; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}
這個程序首先接收一個整數輸入,然后創建4個線程。每個線程負責查找一部分范圍內的因子。線程之間不會重復查找因子。最后,主線程等待所有子線程完成任務。