def modular_pow(base, p, mod):
    """ Computes base^p mod mod using repeated squaring
    """
    ans = 1
    index = 0
    while 1 << index <= p:
        if p & (1 << index):
            ans = (ans * base) % mod
        index += 1
        base = (base * base) % mod
    return ans