def modular_exp(a, b, n):
    """Computes a^b mod n. Complexity O(log(b))"""
    res = 1
    q = a
    while b > 0:
        if b % 2 == 1:
            res = q*res % n
        q = q*q % n
        b //= 2

    return res