4. Write a OpenMP program to find the prime numbers from 1 to n employing parallel for directive. Record both serial and parallel execution times.
PROGRAM:
#include <stdio.h>
#include <math.h>
#include <omp.h>
int is_prime(int num) {
if (num < 2) return 0;
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0)
return 0;
}
return 1;
}
int main() {
int n;
printf("Enter the value of n: ");
scanf("%d", &n);
printf("\nPrime numbers from 1 to %d:\n", n);
for (int i = 1; i <= n; i++) {
if (is_prime(i))
printf("%d ", i);
}
printf("\n");
double start_time, end_time;
start_time = omp_get_wtime();
for (int i = 1; i <= n; i++) {
is_prime(i);
}
end_time = omp_get_wtime();
printf("Serial Time: %f seconds\n", end_time - start_time);
start_time = omp_get_wtime();
#pragma omp parallel for
for (int i = 1; i <= n; i++) {
is_prime(i);
}
end_time = omp_get_wtime();
printf("Parallel Time: %f seconds\n", end_time - start_time);
return 0;
}
OUTPUT:
Enter the value of n: 500
Prime numbers from 1 to 500:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499
Serial Time: 0.000000 seconds
Parallel Time: 0.002000 seconds
📝 Note for Serial Time = 0.000000 seconds
🔹 The serial execution time appears as
0.000000 seconds
because the loop executes very quickly — in less than 1 microsecond.
🔹 Theomp_get_wtime()
function measures time in seconds, and its precision depends on the system.
🔹 On most systems, such tiny durations are rounded to zero when printed with 6 decimal places.