def ipow(a, b, n):
    """calculates (a**b) % n via binary exponentiation, yielding itermediate
       results as Rabin-Miller requires"""
    A = a = a % n
    yield A
    t = 1
    while t <= b:
        t <<= 1
    t >>= 2
    while t:
        A = A * A % n
        if t & b:
            A = A * a % n
        yield A
        t >>= 1
