2
我想做一個程序,使用非常低效的算法,使用POSIX線程計算範圍內的完美數字。我似乎無法把握足夠好的概念來讓我的算法正常工作。我想返回一個完美數字的列表。任何人都可以提供一些建議,如何更好地實現這一點?使用pthreads的完美數字計算器
具體問題: - 我如何才能打印出每個完美數字的1個瞬間? - 如何讓它返回值而不是隻打印值?
來源:
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static void * threadFunc(void *arg) {
int range, start, end;
int i, s, number, mod, divisor, temp, sum;
s = pthread_mutex_lock(&mtx);
/* Takes in a string and pulls out the two integers */
sscanf(arg,"%i-%i", &start, &end);
printf("\nStart: %i\nEnd: %i\n", start, end);
printf("\n");
s = pthread_mutex_unlock(&mtx);
for (number=start; number<=end; number++) { // loop through range of numbers
temp=0,sum=0;
// loops through divisors of a number and sums up whole divisors
for (i=1; i<number; i++) {
//s = pthread_mutex_lock(&mtx);
mod = number % i;
//s = pthread_mutex_unlock(&mtx);
if (mod == 0){
s = pthread_mutex_lock(&mtx);
divisor = i;
sum = divisor + temp;
temp = sum;
s = pthread_mutex_unlock(&mtx);
}
}
//if the sum of whole divisors is equal to the number, its perfect
if (sum == number) {
s = pthread_mutex_lock(&mtx);
printf("%i is a Perfect Number \n", sum);
//return sum somehow;
s = pthread_mutex_unlock(&mtx);
}
}
return NULL;
}
int main(int argc, char *argv[]) {
pthread_t tid[5];
int prefect_number, i, s;
char input[]="1-9999";
for(i=0; i < 5; ++i) {
pthread_create(&tid[i], NULL, &threadFunc, input);
print_thread_info();
}
/* Wait for the perfect number thread to complete, then get result. */
for(i=0; i < 5; ++i)
pthread_join(tid[i],NULL);
return 0;
}