f77coder has asked for the wisdom of the Perl Monks concerning the following question:
i saw this code on a test site and am curious how would Perl implement arithmatic exceptions?
this code will probably bomb if the 1 input array is MIN/MAX_INT or 2 the array is too large, O(n2)
I've been looking around at arbitrary precision libs but looking for a native Perl solution without external libs
bad code
int foo ( int A[], int n ) { int k, m, lsum, rsum; for(k = 0; k < n; ++k) { lsum = 0; rsum = 0; for(m = 0; m < k; ++m) lsum += A[m]; for(m = k + 1; m < n; ++m) rsum += A[m]; if (lsum == rsum) return k; } return -1; }
fixed code
int foo(int arr[], int n) { if (n==0) return -1; long long sum = 0; int i; for(i=0;i<n;i++) sum+=(long long) arr[i]; long long sum_left = 0; for(i=0;i<n;i++) { long long sum_right = sum - sum_left - (long long) arr[i]; if (sum_left == sum_right) return i; sum_left += (long long) arr[i]; } return -1; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: How does Perl handle arithmetic overflows?
by dave_the_m (Monsignor) on Sep 08, 2016 at 10:56 UTC | |
by f77coder (Beadle) on Sep 08, 2016 at 12:37 UTC | |
|
Re: How does Perl handle arithmetic overflows?
by Corion (Patriarch) on Sep 08, 2016 at 10:56 UTC | |
by f77coder (Beadle) on Sep 08, 2016 at 12:37 UTC |