fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <omp.h>
  4.  
  5. #define N 1000 // Size of the array
  6.  
  7. void prefix_sum(int* input, int* output, int n) {
  8. #pragma omp parallel
  9. {
  10. int* temp = (int*)malloc(n * sizeof(int)); // Temporary storage for prefix sums in each thread
  11.  
  12. // Copy input data to temporary array in parallel
  13. #pragma omp for schedule(static)
  14. for (int i = 0; i < n; i++) {
  15. temp[i] = input[i];
  16. }
  17.  
  18. // Compute prefix sums
  19. for (int step = 1; step < n; step *= 2) {
  20. #pragma omp for schedule(dynamic) private(i)
  21. for (int i = step; i < n; i++) {
  22. temp[i] += temp[i - step];
  23. }
  24. #pragma omp barrier // Synchronize threads after each step to ensure correct calculations
  25. }
  26.  
  27. // Copy results to the output array
  28. #pragma omp for schedule(static)
  29. for (int i = 0; i < n; i++) {
  30. output[i] = temp[i];
  31. }
  32.  
  33. free(temp); // Deallocate memory for temporary array
  34. }
  35. }
  36.  
  37. int main() {
  38. int input[N];
  39. int output[N];
  40.  
  41. // Initialize the input array with values 1, 2, 3, ..., N
  42. #pragma omp parallel for
  43. for (int i = 0; i < N; i++) {
  44. input[i] = i + 1;
  45. }
  46.  
  47. // Calculate prefix sums
  48. prefix_sum(input, output, N);
  49.  
  50. // Output the result (print the first few elements for brevity)
  51. printf("Prefix sums:\n");
  52. for (int i = 0; i < 10; i++) {
  53. printf("%d ", output[i]);
  54. }
  55. printf("\n");
  56.  
  57. return 0;
  58. }
  59.  
Success #stdin #stdout 0s 5280KB
stdin
Standard input is empty
stdout
Prefix sums:
1 3 7 13 23 37 57 83 119 165