Skip to content

Commit c46c3c2

Browse files
authored
Merge pull request #20 from ahiliitb/product-of-negative-number
added support for negative number as well as zero for vector product (#Issue 6)
2 parents 851e87d + f0a1676 commit c46c3c2

File tree

4 files changed

+28
-1
lines changed

4 files changed

+28
-1
lines changed
File renamed without changes.

prod

16.8 KB
Binary file not shown.

src/prod.cpp

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,26 @@ double compute_log_sum(int* a, int size, int num_threads) {
1616

1717
#pragma omp parallel for default(shared) reduction(+:log_sum) num_threads(num_threads)
1818
for (int i = 0; i < size; i++) {
19-
log_sum += log(a[i]);
19+
log_sum += log(abs(a[i]));
2020
}
2121

2222
return log_sum;
2323
}
2424

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+
2539
// Function to compute the product using the sum of logarithms
2640
double compute_product(double log_sum) {
2741
return exp(log_sum);
@@ -38,12 +52,25 @@ int main(int argc, char *argv[]) {
3852
// Initialize array
3953
initialize_array(a, ARR_SIZE, 2);
4054

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+
4163
// Compute the log sum in parallel
4264
double log_sum = compute_log_sum(a, ARR_SIZE, num_threads);
4365

4466
// Compute the product using the log sum
4567
double prod = compute_product(log_sum);
4668

69+
if(neg_and_zero_count.first%2 == 1)
70+
{
71+
prod = -prod;
72+
}
73+
4774
// Print the result
4875
cout << "Product=" << prod << endl;
4976

wrong_sum

17.1 KB
Binary file not shown.

0 commit comments

Comments
 (0)