0

I am testing a simple linear diophantine equations code. Here is the code:

a = 3
b = 4
n = 67

i = 0
while True:
    if i * a <= n:
        if (n - (i * a)) % b == 0:
                yy = int((n - (i * a)) / b)
                print("{0} x {1} + {2} x {3} = {4}".format(a, i, b, yy, n))
        i = i + 1
    else:
        print("No possible solution!")
        break

When the code is run, it is able to find the possible x and y in this equation (which is fine). But, what I can't figure out is why is the print "No Possible solution!" is getting printed together with the answer. The else block is suppose to appear only if a solution is not possible e.g a = 3, b = 4 and n = 2.

Any advice will be appreciated.

2
  • You only have one break, so the loop can only end after printing that. Even if it takes the first branch at first, it will continue looping until it breaks. Commented Jan 12, 2020 at 6:59
  • It would be helpful to include the output in the question. Commented Jan 12, 2020 at 7:02

2 Answers 2

1

print("No possible solution!") is inside the else case so it will execute regardless of whether any solutions were found or not.

Here is one way to fix it where a boolean variable keeps track of whether a solution was found or not and prints the message based on the state of that variable:

a = 3
b = 4
n = 2

i = 0
solution_found = False
while True:
    if i * a <= n:
        if (n - (i * a)) % b == 0:
            yy = int((n - (i * a)) / b)
            print("{0} x {1} + {2} x {3} = {4}".format(a, i, b, yy, n))
            solution_found = True
        i = i + 1
    else:
        break

if not solution_found:
    print("No possible solution!")
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the explanation! Silly me, couldn't think of this at all!
0

Use flag to identify solution is available or not.

a = 3
b = 4
n = 67

i = 0
isSolutionAvailable=False
while True:
    if i * a <= n:
        if (n - (i * a)) % b == 0:
                yy = int((n - (i * a)) / b)
                print("{0} x {1} + {2} x {3} = {4}".format(a, i, b, yy, n))
                isSolutionAvailable=True
        i = i + 1
    else:
        break
if(not(isSolutionAvailable)):
    print("No possible solution!")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.