@@ -16,12 +16,26 @@ double compute_log_sum(int* a, int size, int num_threads) {
16
16
17
17
#pragma omp parallel for default(shared) reduction(+:log_sum) num_threads(num_threads)
18
18
for (int i = 0 ; i < size; i++) {
19
- log_sum += log (a[i]);
19
+ log_sum += log (abs ( a[i]) );
20
20
}
21
21
22
22
return log_sum;
23
23
}
24
24
25
+ // Function to find number of negative numbers in parallel
26
+ pair<int , int > count_negative_and_zero (int * a, int size, int num_threads) {
27
+ int negative_count = 0 , zero_count = 0 ;
28
+ int i;
29
+
30
+ #pragma omp parallel for private(i) reduction(+:negative_count, zero_count) num_threads(num_threads)
31
+ for (i = 0 ; i < size; i++) {
32
+ if (a[i] < 0 )negative_count++;
33
+ else if (a[i] == 0 )zero_count++;
34
+ }
35
+
36
+ return {negative_count, zero_count};
37
+ }
38
+
25
39
// Function to compute the product using the sum of logarithms
26
40
double compute_product (double log_sum) {
27
41
return exp (log_sum);
@@ -38,12 +52,25 @@ int main(int argc, char *argv[]) {
38
52
// Initialize array
39
53
initialize_array (a, ARR_SIZE, 2 );
40
54
55
+ pair<int , int > neg_and_zero_count = count_negative_and_zero (a, ARR_SIZE, num_threads);
56
+ if (neg_and_zero_count.second > 0 )
57
+ {
58
+ // Print the result
59
+ cout << " Product=" << 0 << endl;
60
+ return 0 ;
61
+ }
62
+
41
63
// Compute the log sum in parallel
42
64
double log_sum = compute_log_sum (a, ARR_SIZE, num_threads);
43
65
44
66
// Compute the product using the log sum
45
67
double prod = compute_product (log_sum);
46
68
69
+ if (neg_and_zero_count.first %2 == 1 )
70
+ {
71
+ prod = -prod;
72
+ }
73
+
47
74
// Print the result
48
75
cout << " Product=" << prod << endl;
49
76
0 commit comments