-3

I am trying to write a code which can input 3 long int variables, a, b, c. The code should find all integer (x,y) so that ax+by = c, but the input values can be up to 2*10^9. I'm not sure how to do this efficiently. My algorithm is O(n^2), which is really bad for such large inputs. How can I do it better? Here's my code-

typedef long int lint;

struct point
{
lint x, y;
};

int main()
{
lint a, b, c;
vector <point> points;
cin >> c >> a >> b;
for(lint x = 0; x < c; x++)
    for(lint y = 0; y < c; y++)
    {
        point candidate;
        if(a*x + b*y == c)
        {
            candidate.x = x;
            candidate.y = y;
            points.push_back(candidate);
            break;
        }
    }
}
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • Can't `x` and `y` be negative ? – Aditi Rawat Dec 01 '17 at 07:47
  • You should check the [Extended Euclidean Algorithm](https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm), which is the fastest algorithm (as far as I know) to solve this diophantine equations. – Francisco Gallego Salido Dec 01 '17 at 07:49
  • Your code ASSUMES that `c` is positive, and only checks non-negative values of `x` and `y`. Under the same constraints, it would be trivial to eliminate the inner loop and detect if there are ANY values. Then a simpler loop, if there is one value, to find the others. Without those constraints, the number of potential pairs is infinite. – Peter Dec 01 '17 at 08:08
  • I should have mentioned in the post, a, b, and c must be positive values. – Kaustubh Varshney Dec 01 '17 at 13:52

1 Answers1

0

Seems like you can apply a tiny bit of really trivial math to solve for y for any given value of x. Starting from ax + by = c:

ax + by = c

by = c - ax

Assuming non-zero b1, we then get:

y = (c - ax) / b

With that in hand, we can generate our values of x in the loop, plug it into the equation above, and compute the matching value of y and check whether it's an integer. If so, add that (x, y) pair, and go on to the next value of x.

You could, of course, make the next step and figure out which values of x would result in the required y being an integer, but even without doing that we've moved from O(N2) to O(N), which is likely to be plenty to get the task done in a much more reasonable time frame.


  1. Of course, if b is 0, then the by term is zero, so we have ax = c, which we can then turn into x = c/a, so we then just need to check that x is an integer, and if so all pairs of that x with any candidate value of y will yield the correct c.
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111