Euclidean Division Theorem program

Question:

I write a code to count quotient and remainder according to Euclidean division Theorem.

a,b=input().split()
a=int(a)
b=int(b)

if(a<0 and b>0):
    q=int(a/b)-1
    r=a-(b*q)
    print(q,end=" ")
    print(r)

elif(a>0 and b<0):
    q=int(a/b)
    r=a-(b*q)
    print(q,end=" ")
    print(r)

elif(a>0 and b>0):
    q=int(a/b)
    r=a-(b*q)
    print(q,end=" ")
    print(r)

elif(a<0 and b<0):
    q=int(a/b)-1
    r=a-(b*q)
    print(q,end=" ")
    print(r)    

Is here any bug to count quotient and remainder according to Euclidean division Theorem..??Acctually this is uri online judge’s 1837 no problem.I write this code and submit but showing 40%wrong answer.program description:https://www.urionlinejudge.com.br/judge/en/problems/view/1837

Asked By: Rakibul Islam

||

Answers:

The wrong answers are due to the fact that your current implementation does not ensure that the calculated r will be a positive number when a,b < 0. In fact, if you check the link provided you will see that the theorem defines 0 ≤ r < |b|

Testing your current algorithm with input values a = -7 and b = -3 you will get q = 1 and r = -4. But as said we need r ≥ 0

Try the following code again with input values a = -7 and b = -3. This time you will get q = 3 and r = 2, which satisfies as well the a = b × q + r equation: -7 = -3 x 3 + 2

Finally – just to avoid misunderstandings – I added a condition to control and explicitly cover those inputs where b = 0, another situation not accepted by the Euclidean Division Theorem

def euclidean_division(a, b):

    if(a < 0 and b > 0):
        q = int(a/b) - 1
        r = a - (b*q)

    elif(a > 0 and b < 0):
        q = int(a/b)
        r = a - (b*q)

    elif(a > 0 and b > 0):
        q = int(a/b)
        r = a - (b*q)

    elif(a < 0 and b < 0):
        q = int((a+b)/b)
        r = a - (b*q)

    return q, r  

def main():
    print("Please insert two integer values separated by a space")
    print("NOTE: the second integer is NOT allowed to be equal to zero")
    first_input, second_input = input().split()
    first_int=int(first_input)
    second_int=int(second_input)

    if(second_int != 0):
        first_output, second_output = euclidean_division(first_int, second_int)
        print("q = " + str(first_output) + " r = " + str(second_output))
    else:
        print("Second integer must be other than 0")
        print("Try againn")
        main()

if __name__ == "__main__":
    main()

NOTE: this example proves also the importance of having r ≥ 0 to guarantee the uniqueness of the solution

Answered By: Antonino
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.