0

Problem: Write a program that solves the linear equation for x, where ax = b in integers.

Given two user inputs, a and b (a may be zero), print:

  • a single integer solution for x if it exists or
  • "no solution" or
  • "no integer solution" if the answer is a floating point number or
  • "many solutions"

How can I solve this using if elif and else statements? Here's my code so far:

a = int(input())
b = int(input())

if a == 0 and b == 0:
  print("many solutions")
elif b //a == 0:
  print(b // a)
elif b//a != 0:
  print("no integer solution")
elif a== 0 and b!= 0 or b==0 and a!=0:
  print("no solution")
lucidbrot
  • 5,378
  • 3
  • 39
  • 68

2 Answers2

2

In your 'elif' statements, you have given:

elif b //a == 0:
    print(b // a)
elif b//a != 0:
    print("no integer solution")

The operator '//' is used for integer division i.e. leaving no remainder. Hence the elif statement will always execute.

I assume you're checking the remainder. For that use '%'. This returns the remainder

Ismail Hafeez
  • 730
  • 3
  • 10
0

print:

  • a single integer solution for x if it exists or "no solution"
  • or "no integer solution" if the answer is a floating point number
  • or "many solutions".

Let's first think about the math: You have the equation a*x = b and you want to find x. The first step is to solve this equation on paper so that you get it to the form x = ....

Now you will have a division in there. And divisions are always risky because if you divide by zero, you will get a ZeroDivisionError. So In the program, I would first of all handle that case. Think about what it should do when that variable is indeed zero.

so i dont know in what condition would x have 1 solution in this linear equation

In most cases. The only reason to have more or less than 1 solution is if either a division by zero happens or there is no integer solution at all.

To check if there is an integer solution, you can use the modulo operator. Or you could compute the integer result and then compute it backwards again to see if you get the result that was your input.

To code this, I think you have understood how if and elif work. Just make sure you have the same number of whitespace in front of the indented lines that should be at the same level. Otherwise it will probably not run.

lucidbrot
  • 5,378
  • 3
  • 39
  • 68