If you want 100% CPU, you need to use more than 1 core. To do that, you need multiple threads.
Here’s a parallel version using OpenMP:
I had to increase the limit to 1000000
to make it take more than 1 second on my machine.
#include <stdio.h>
#include <time.h>
#include <omp.h>
int main() {
double start, end;
double runTime;
start = omp_get_wtime();
int num = 1,primes = 0;
int limit = 1000000;
#pragma omp parallel for schedule(dynamic) reduction(+ : primes)
for (num = 1; num <= limit; num++) {
int i = 2;
while(i <= num) {
if(num % i == 0)
break;
i++;
}
if(i == num)
primes++;
// printf("%d prime numbers calculated\n",primes);
}
end = omp_get_wtime();
runTime = end - start;
printf("This machine calculated all %d prime numbers under %d in %g seconds\n",primes,limit,runTime);
return 0;
}
Output:
This machine calculated all 78498 prime numbers under 1000000 in 29.753 seconds
Here’s your 100% CPU: