Subtractions (Codeforces 267A)
Tags: Math, number theory

You've got two numbers. As long as they are both larger than zero, they go through the same operation: subtract the lesser number from the larger one. If they equal substract one number from the another. For example, one operation transforms pair (4,17) to pair (4,13), it transforms (5,5) to (0,5).You've got some number of pairs (ai, bi). How many operations will be performed for each of them?

Input: The first line contains the number of pairs n (1  ≤  n  ≤  1000). Then follow n lines, each line contains a pair of positive integers ai, bi (1  ≤  ai,  bi  ≤  109).

Output: Print the sought number of operations for each pair on a single line.


Sample Inputs:
2
4 17
7 987654321

Sample Outputs:
8
141093479

Solution (Python):
def substract(a, b):
    if a > b:
        total = 0
        while a > 0 and b > 0:
            total += int(a / b)
            a = a % b
            if a > 0:
                total += int(b / a)
                b = b % a
        return total
    if a < b:
        total = 0
        while a > 0 and b > 0:
            total += int(b / a)
            b = b % a
            if b > 0:
                total += int(a / b)
                a = a % b
        return total
    if a == b:
        return 1
n = int(input())
lst = []
for i in range(0, n):
    (a, b) = map(int, input().split())
    lst.append(substract(a, b))
for i in lst:
    print(i)

Solution (Python):
for _ in range(int(input())):
    (a, b) = map(int, input().split())
    if a > b:
        c = a // b
        a = a % b
    else:
        c = b // a
        b = b % a
    while min(a, b) > 0:
        if a > b:
            c += a // b
            a = a % b
        else:
            c += b // a
            b = b % a
    print(c)

Solution (Python):
a = int(input())
while a > 0:
    b = [int(i) for i in input().split()]
    c = 0
    while b[0] * b[1] != 0:
        c += b[1] // b[0]
        (b[0], b[1]) = (b[1] % b[0], b[0])
    print(c)
    a -= 1