使用pthread进行素数但得到错误的结果

时间:2016-03-04 09:07:09

标签: c

我想更改此程序,以便如果用户输入数字N,则它会将素数提供给N值。因为我是新手,我无法理解。请向我解释我错过了什么。 MAX_PRIME是我的输入论证,候选人是我想要计算的素数。

#include <pthread.h>
#include <stdio.h>
#include<stdlib.h>
#include<math.h>



int NUM_THREADS;
pthread_t *thread;
int MAX_PRIME;
int current = 1;
int candidate;

pthread_mutex_t thread_flag_mutex;

int get_next_candidate()
{
    pthread_mutex_lock (&thread_flag_mutex);
    int result=current++;
    pthread_mutex_unlock (&thread_flag_mutex);

    return result;
}


int compute_prime(int numPrime)
{
    int candidate = 2;
    while (1)
    {
        int factor;
        int is_prime = 1;

        /* Test primality by successive division.  */
        for (factor = 2; factor < MAX_PRIME; ++factor)
        {
            if (candidate % factor == 0)
            {
                is_prime = 0;
                break;
            }
        }

        if (is_prime)
        {
            if (--numPrime == 0)
            {
                return candidate;
            }
        }    
        ++candidate;
    }

    return 0;
}


void* prime_job(void* t)
{

    long tid = (long ) t , total = 0 , result=0;


    printf("Thread %ld starting...\n", tid);

    while((candidate=get_next_candidate())<=MAX_PRIME){
        result=compute_prime(candidate);    
        printf("Thread %ld found prime: %ld\n",tid, result);

        ++total;
    }

    pthread_exit((void*) total);
}


//******************************* main 
int main (int argc, char **argv)
{
    if (argc<=1){
        printf("usag : prime MaxNumber [NUM_THREADS]");
        return 0;
    }

    else if (argc==2){
        //setting up the default thread value 
        MAX_PRIME=atoi(argv[1]);
        NUM_THREADS =2;
    }

    else{
        MAX_PRIME=atoi(argv[1]);
        NUM_THREADS=atoi(argv[2]);

    }


    //**************************** allocaion of memory

    candidate = malloc((candidate+1)*sizeof(int));
    thread = malloc(NUM_THREADS*sizeof(pthread_t));

    long t;

    // Start threads
    for (t = 0; t < NUM_THREADS; t++)
        pthread_create(&thread[t], NULL, prime_job, (void *) t);

    // Join threads
    for (t = 0; t < NUM_THREADS; t++)
    {
        void* numPrimesCalc;
        pthread_join(thread[t], &numPrimesCalc);
        printf("Thread %ld joined, calculated %ld prime numbers\n", t, (long) numPrimesCalc);
    }

    /* Print the largest prime it computed.  */

    pthread_exit(NULL);
}

1 个答案:

答案 0 :(得分:0)

int compute_prime(int numPrime)
{
    int candidate = 2;
    while (1)
    {
        int factor;
        int is_prime = 1;

        /* Test primality by successive division.  */
        for (factor = 2; factor < MAX_PRIME; ++factor)
        {
            if (candidate % factor == 0)

如果您尝试测试numPrime是否为素数,则numPrime需要位于%的左侧。否则,您将完全测试错误的号码。

您的for循环需要在测试编号之前停止。对于大于零的所有x % xx将为零。因此,如果您测试包含您正在测试素数的数字的因素,您将永远找不到素数。

另外,while (1)到底是什么?这段代码看起来像是货物崇拜编程的结果,因为它们帮助解决了完全不同的问题而没有理解。