Prime number calculation fun

前端 未结 18 1813
深忆病人
深忆病人 2020-12-05 15:32

We\'re having a bit of fun here at work. It all started with one of the guys setting up a Hackintosh and we were wondering whether it was faster than a Windows Box of (nearl

18条回答
  •  旧时难觅i
    2020-12-05 15:47

    Here's my solution... its fairly fast... it calculates the primes between 1 and 10,000,000 in 3 seconds on my machine (core i7 @ 2.93Ghz) on Vista64.

    My solution is in C, but I am not a professional C programmer. Feel free to criticize the algorithm and the code itself :)

    #include
    #include
    #include
    #include
    
    //5MB... allocate a lot of memory at once each time we need it
    #define ARRAYMULT 5242880 
    
    
    //list of calculated primes
    __int64* primes; 
    //number of primes calculated
    __int64 primeCount;
    //the current size of the array
    __int64 arraySize;
    
    //Prints all of the calculated primes
    void PrintPrimes()
    {
        __int64 i;
        for(i=0; i than the square of the
                    //candidate, the candidate is a prime... so we can add it to the list
                    if(primes[j] > square)
                    {
                        //our array has run out of room, so we need to expand it
                        if(primeCount >= arraySize)
                        {
                            int k;
                            __int64* newArray = (__int64*)malloc(sizeof(__int64) * (ARRAYMULT + arraySize));
    
                            for(k=0; k

提交回复
热议问题