Prime numbers calculator

Tips and tricks on programming in T++

Prime numbers calculator

Postby tonic » Fri Apr 30, 2010 12:27 pm

Code: Select all
/*
    primes.tpp: parallel calculation of the prime number by given index
*/

#ifdef _WIN32
#include <time.h>
#else
#include <sys/time.h>
#endif

#define num 10000
long primes[num];

tfun long fill() {
    int k = 2;
    bool is;
    primes[1] = 2;
    primes[2] = 3;
    for (long i=5, step=4; k<num; i+= (step=6-step)) {
        is = true;
        for (int j=1; (j<=k) && (primes[j]*primes[j]<=i) && is; ++j) {
            if (!(i%primes[j])) is = false;
        }
        if (is) primes[++k] = i;
    }
    return 1;
}
void t_fill() {
    const int nnodes = ts::realsuperSize; 
#ifdef _WIN32
    ts::TVar<long>* current = new ts::TVar<long> [nnodes];
#else
    tval long current[nnodes];
#endif
    long s=0;
    for (int node=0; node < nnodes; ++node) {
        tct(atRank((nnodes - node - 1)));
        current[node] = fill();
        ts::sleep(0.0001/nnodes);
    }
    for (int node=0; node < nnodes; ++node) {
        s += current[node];   
    }
}
bool prime (long j) {
    bool is = true;
    for (int k=1; is && primes[k]*primes[k]<=j; ++k) if (!(j%primes[k])) is = false;
    return is;
}
tfun long nprimes (long k, long tt) {
    long np=0;
    for (long i=k; i<k+tt; ++i) if (prime(i)) ++np;
    return np;
}
tfun int main (int argc, char* argv[]) {
    long n, cons = 600;
    long j = 2, tt, tj;
    bool first;
    const int nnodes = 3*ts::realsuperSize;
#ifdef _WIN32
    ts::TVar<long>* current = new ts::TVar<long> [nnodes];
#else
    tval long current[nnodes];
#endif
    if (argc < 2) {
        printf("Please specify an index of the prime number.\n");
        return 1;
    }
    n = atol(argv[1]);
    first = true;
    t_fill();
    for (long i=0; i<n;) {
        tj = 6*(n-i);
        if (tj > cons) {       
            tj= 6*(n-i)/nnodes;
            for (int node=0; node < nnodes; ++node) {
                current[node] = nprimes(j, tj);
                j += tj;
                ts::sleep(0.0001/nnodes);
            }
            for (int node=0; node < nnodes; ++node) {
                i += current[node];
            }
        }
        else {
            if (first) {
                first = false;
                if (prime(j)) ++i;
            }
            else if (prime(++j)) ++i;
        }
    }
    printf("prime=%ld\n",j);
    return 0;
}


To build it under Windows issue the following command:
t++ primes.tpp

To build it under Linux issue the following command:
t++ -opt -o primes primes.tpp

To run Primes application on the multicore computer, issue this command:
primes 9000000 -tct enableSMP

To run Primes application on the computing cluster, issue this command:
mpirun -np 4 primes 9000000
tonic
 
Posts: 14
Joined: Tue Jun 10, 2008 2:50 pm

Return to T++ language

Who is online

Users browsing this forum: No registered users and 1 guest

cron