
Originally Posted by
Alpha
well the question here is, do you want to find all the prime numbers up to a value or find value number of primes?
that method finds all the primes up to value.
why start at 2 to find every even number to not be prime? its a waste of resources every other itteration. really, you only need to check if a number is prime by checking its divisability by every prime number <= its sqrt.
You are very right.
Here is muffinPrime. (
)
Code:
#include <string.h>
#include <windows.h>
#include <math.h>
#include <time.h>
typedef struct range {
int start;
int stop;
} MYDATA, *PMYDATA;
int is_prime(int number) {
int i = 2;
for (i = 2; i <= sqrt(number); i++) {
if (number % i == 0) {
return 0;
}
}
return 1;
}
void WINAPI test(LPVOID lpParam) { //The benchmark itself
PMYDATA pDataArray;
int start, stop, primes;
pDataArray = (PMYDATA)lpParam;
start = pDataArray->start;
stop = pDataArray->stop;
primes = 0;
while (primes <= stop) {
if (is_prime(start) == 1) {
primes++; //If the number is prime, add 1 to primes found
}
start += 2;
}
}
int main() {
HANDLE hThread[16]; //For a maximum of 16 processors
PMYDATA pDataArray[16];
SYSTEM_INFO system_info;
int i, start, max, stop, start_time, end_time, threads, size;
char* buffer;
GetNativeSystemInfo(&system_info);
threads = system_info.dwNumberOfProcessors; //Get number of processors
i = 0;
start = 1;
max = 1000000;
stop = max/threads;
start_time = time(NULL);
size = strlen("Calculating prime numbers on threads!\n") + 10;
buffer = malloc(size);
sprintf(buffer, "Calculating %d prime numbers on %d threads!\n", max, system_info.dwNumberOfProcessors);
MessageBox(NULL, buffer, "Starting benchmark!", MB_OK);
for (i = 0; i < threads; i++) {
pDataArray[i] = (PMYDATA)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(MYDATA));
pDataArray[i]->start = start;
pDataArray[i]->stop = stop;
hThread[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)test, pDataArray[i], 0, NULL);
start += max/threads;
stop += max/threads;
}
WaitForMultipleObjects(threads, hThread, TRUE, INFINITE);
for (i = 0; i < threads; i++) {
CloseHandle(hThread[i]);
HeapFree(GetProcessHeap(), 0, pDataArray[i]);
pDataArray[i] = NULL;
}
end_time = time(NULL);
size = strlen("It took seconds to calculate prime numbers on threads.\n") + 16;
buffer = malloc(size);
sprintf(buffer, "It took %d seconds to calculate %d prime numbers on %d threads.\n", end_time-start_time, max, threads);
MessageBox(NULL, buffer, "Finished benchmark!", MB_OK);
return 1;
}
Bookmarks