- Sep 19, 2000
- 10,286
- 145
- 106
I thought it might be fun. for my CS class I created a prime finding function (to aid in reducing a fraction) and slowly I have been trying to shave off the extra milliseconds. I cannot use Euclid's algorithm btw. Below is what I have as a prime finding function.
As a note, "primes" is static. num represents the number of primes to find and the extra comments where given more to satisfy the grader.
BTW, one of the problems I ran into is finding some meaningful way to implement some sort of rate control (I big numbers need more primes to reduce then small numbers do) currently I just find the 5 new primes each time the function is called.
So, any tips for a faster function?
(don't use the "attach code" button, it is unreadable. also, the best way to get a spaced copy of the code is to quote me and then copy the stuff in the quotations.)
As a note, "primes" is static. num represents the number of primes to find and the extra comments where given more to satisfy the grader.
BTW, one of the problems I ran into is finding some meaningful way to implement some sort of rate control (I big numbers need more primes to reduce then small numbers do) currently I just find the 5 new primes each time the function is called.
So, any tips for a faster function?
void findPrime(int num)
{
int lastPrime;
int i;
bool valid;
int count = 0;
unsigned int* fPrime;
fPrime = new unsigned int[size + num];
for (i = 0; i < size; i++)
fPrime = primes;
delete[] primes;
primes = NULL;
lastPrime = fPrime[size - 1];
while (count < num)
{
valid = true;
// Skip 2 because no prime after 3 is next to another
lastPrime += 2;
i = 1; // start at 3 rather then 2 because of the last statement
while (i < size && valid)
{
// lastPrime isn't prime if it can be divided evenly by a prime
if (!(lastPrime % fPrime))
valid = false;
++i;
}
// If all went well, add the prime to the prime list.
if (valid)
{
fPrime[size] = lastPrime;
++size;
++count;
}
}
primes = fPrime;
fPrime = NULL;
}
(don't use the "attach code" button, it is unreadable. also, the best way to get a spaced copy of the code is to quote me and then copy the stuff in the quotations.)