gpt4 book ai didi

c - C中的非递归阶乘

转载 作者:太空宇宙 更新时间:2023-11-04 08:49:42 26 4
gpt4 key购买 nike

我有一个简单的问题要问你。我编写了这段代码来计算一个数字的阶乘而不用递归。

int fact2(int n){
int aux=1, total = 1;
int i;
int limit = n - 1;
for (i=1; i<=limit; i+=2){
aux = i*(i+1);
total = total*aux;
}
for (;i<=n;i++){
total = total*i;
}
return total;

}

如您所见,我的代码使用循环展开来优化执行中的时钟周期。现在我被要求向同一代码添加双向并行性,知道怎么做吗?

最佳答案

您可以使用 ptherads 库创建两个独立的线程。每个线程应该做一半的乘法。我可以整理以下解决方案。

#include <pthread.h>

typedef struct {
int id;
int num;
int *result;
} thread_arg_t;

void* thread_func(void *arg) {
int i;
thread_arg_t *th_arg = (thread_arg_t *)arg;
int start, end;
if(th_arg->id == 0) {
start = 1;
end = th_arg->num/2;
} else if (th_arg->id == 1) {
start = th_arg->num / 2;
end = th_arg->num + 1;
} else {
return NULL;
}
for(i=start; i < end; i++) {
th_arg->result[th_arg->id] *= i;
}
return NULL;
}

int factorial2(int n) {
pthread_t threads[2];
int rc;
int result[2];
thread_arg_t th_arg[2];
for(i=0; i<2; i++) {
th_arg[i].id = i;
th_arg[i].num = n;
th_arg[i].result = result;
rc = pthread_create(&threads[i], NULL, thread_func, (void *)&th_arg[i]);
if (rc){
printf("pthread_create() failed, rc = %d\n", rc);
exit(1);
}
}

/* wait for threads to finish */
for(i=0; i<2; i++) {
pthread_join(thread[i], NULL);

/* compute final one multiplication */
return (result[0] * result[1]);
}

pthread 库实现应该负责为您并行处理两个线程的工作。此外,这个示例可以通过少量修改推广到 N 个线程。

关于c - C中的非递归阶乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20110466/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com