1

I am trying to solve ax + by = n.

When I put n = 7, it solves the equation correctly as X = 2 and Y = 1. But when I put n = 1, it does not solve the equation. Even though, this equation has valid integer solution, X = 17, Y = -11. here is my full program.

#include <iostream>
using namespace std;

void PrintXY(int a, int b, int n)
{
    for (int i = 0; i * a <= n; i++) {

        if ((n - (i * a)) % b == 0) {
            cout << "x = " << i << ", y = "
                << (n - (i * a)) / b;
            return;
        }
    }

    cout << "No solution";
}

int main()
{
    int a = 2, b = 3, n = 1;
    PrintXY(a, b, n);
    return 0;
}

Output when n = 7:

x = 2, y = 1

Output when n = 1:

No solution

Reasoning. 2*(2) + 3*(1) - 7 = 4 + 3 - 7 = 0

2*(17) + 3*(-11) - 1 = 34 - 33 - 1 = 0

Both equations solve to give 0. But what is wrong in my program that is causing it to give "No Solution".

Sebastian
  • 1,834
  • 2
  • 10
  • 22

1 Answers1

2

The problem is with the termination condition:

i*a<=n

This(n>=a*i) need not be true, and is especially not true in case of the solution (ie X=17, Y=-11). Which seems reasonable - Without any bounds(limits) on the answer(either X or Y) , how would you find the solution to a linear equation(with an infinite possible range) in a closed for loop ?

Mark B.
  • 329
  • 2
  • 16