-2

This is the code for the Triangle problem in codility that is throwing me an arithmetic overflow error.

int solution(vector<int> &A) {

    int i, n;
    n=A.size();
    sort(A.begin(), A.end());
    for(i=0; i<n-2; i++)
    {
        if((A[i]+A[i+1]>A[i+2])&&(A[i]+A[i+2]>A[i+1])&&(A[i+1]+A[i+2]>A[i]))
        {
            return 1;
        }
    }
    return 0;
}

It passes all the tests except for the 'extreme_arith_overflow1 overflow test, 3 MAXINTs' saying the code returns 0 but it expects 1. Anybody have any idea on how to fix this?

cs95
  • 379,657
  • 97
  • 704
  • 746
monkikat
  • 33
  • 1
  • 4
  • 2
    First of all make sure that you don't go out of bounds of your vector. (which you will do with the code you currently show) Secondly perhaps use `unsigned int` instead, (if no value can be negative) or maybe `long long` (or `unsigned long long`) for a 64-bit type? Also, you should probaby be doing some input validation to make sure the input you read is valid to begin with. – Some programmer dude Jun 03 '20 at 09:37
  • 1
    You store `A.size()` in `n` and then you loop until `i – Thomas Sablik Jun 03 '20 at 09:43
  • @Someprogrammerdude yesss thanks i fixed the out of bounds issue and validated input :) – monkikat Jun 03 '20 at 12:43

1 Answers1

0

You store A.size() in n and then you loop until i<n and access A[i+2]. In the error cases this is A[A.size()] or even A[A.size()+1]. It's out of bounds. Fix the range of the loop.

The next problem occurs when the sum is larger than INT_MAX. Use the difference instead of the sum to avoid overflow. Remember that the elements are sorted with A[i] <= A[i+1] <= A[i+2]

int solution(vector<int> &A) {
    if (A.size() < 3) return 0;
    const auto n = A.size() - 2;
    std::sort(A.begin(), A.end());
    for(decltype(n) i = 0; i < n; ++i) {
        if((A[i]>A[i+2]-A[i+1])&&(A[i+2]>A[i+1]-A[i])&&A[i]>0) {
            return 1;
        }
    }
    return 0;
}
Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62