'''python
def solve(a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    if not (1 <= a < L <= 2**1024):
        raise ValueError("条件 1 ≤ a < L ≤ 2^1024 を満たしていません。")
        current = a % L
        n = 10 ** 5
        for _ in range(n):
            result.append(current)
            current = (current * current) % L

    return result
'''


'''python
def solve(a: int, L: int) -> list[int]:
    result: list[int] = []
    result = [a]
    for _ in range(n - 1):
        result.append(result[-1] ** 2 % L)

    return result
    if not (1 <= a < L <= 2**1024):
        raise ValueError("条件 1 ≤ a < L ≤ 2^1024 を満たしていません。")
        current = a % L
        n = 10 ** 5
        for _ in range(n):
            result.append(current)
            current = (current * current) % L

    return result
'''


'''python
def solve(a: int, L: int) -> list[int]:
    result = [a]
    for _ in range(n - 1):
        result.append(result[-1] ** 2 % L)

    return result
    if not (1 <= a < L <= 2**1024):
        raise ValueError("条件 1 ≤ a < L ≤ 2^1024 を満たしていません。")
        current = a % L
        n = 10 ** 5
        for _ in range(n):
            result.append(current)
            current = (current * current) % L

    return result
'''


'''python
def solve(n: int, a: int, L: int) -> list[int]:
    result = [a]
    for _ in range(n - 1):
        result.append(result[-1] ** 2 % L)

    return result
    if not (1 <= a < L <= 2**1024):
        raise ValueError("条件 1 ≤ a < L ≤ 2^1024 を満たしていません。")
        current = a % L
        n = 10 ** 5
        for _ in range(n):
            result.append(current)
            current = (current * current) % L

    return result
'''


'''python
def solve(n: int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:

    v = a
    for i in range(n):
    	result.append(v)
    	v = (v ** 2) % L

    return result
'''


'''python
def solve(n: int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    for _ in range(n):
        result.append(a)
        a = a * a % L
    return result
'''


'''python
def solve(n: int, a: int, L: int) -> list[int]:
    result: list[int] = []

    current_value = 1  # This will hold a^(2^k) mod L, starting with a^(2^0) = a^1 mod L
    for k in range(n):
        if k == 0:
            current_value = a % L  # a^(2^0) mod L
        else:
            current_value = (current_value * current_value) % L  # a^(2^k) = (a^(2^(k-1)))^2 mod L

        result.append(current_value)

    return result
'''


'''python
def solve(a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    val = a
    result.append(val % L)
    for i in range(k):
        val = (a ** 2) % L
        result.append(val)
    return result
'''


'''python
def solve(n, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    val = a
    result.append(val % L)
    for i in range(n):
        val = (a ** 2) % L
        result.append(val)
    return result
'''


'''python
def solve(n, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    val = a
    result.append(val % L)
    for i in range(n):
        val = (val ** 2) % L
        result.append(val)
    return result
'''


'''python
def solve(n, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    val = a
    result.append(val % L)
    for i in range(n - 1):
        val = (val ** 2) % L
        result.append(val)
    return result
'''


'''python
def solve(a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    for _ in range(n):
        result.append(a % L)
        a = a * a
    return result
'''


'''python
def solve(a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    for _ in range(n):
        result.append(a % L)
        a = (a * a) % L
    return result
'''


'''python
def solve(a: int, L: int, n: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    for _ in range(n):
        result.append(a % L)
        a = (a * a) % L
    return result
'''


'''python
def solve(a: int, L: int, n: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    for _ in range(n):
        result.append(a)
        a = (a * a) % L
    return result
'''


'''python
def solve(n: int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    for _ in range(n):
        result.append(a)
        a = (a * a) % L
    return result
'''


'''python
def solve(n: int, a: int, L: int) -> list[int]:
    result: list[int] = []
    x = a % L
    for _ in range(n):
        result.append(x)
        x = (x * x) % L
    return result
'''


'''python
def solve(n: int, a: int, L: int) -> list[int]:
    result: list[int] = []

    for _ in range(n):
        result.append(a)
        a = (a * a) % L

    return result
'''


'''python
def solve(a: int, L: int) -> list[int]:
    result: list[int] = []
    record = {}
    i = 0
    while True:
        a2modL = pow(a, 2**i, L)
        if a2modL in record:
            break
        record[a2modL] = i
        result.append(a2modL)
        i += 1
    return result
'''


'''python
def solve(a: int, L: int) -> list[int]:
    result: list[int] = []

    record = {}
    val = a % L
    i = 0

    while val not in record:
        record[val] = i
        result.append(val)
        val = (val * a) % L
        i += 1

    return result
'''


'''python
def solve(n: int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    for i in range(n):
        result.append(a)
        a *= a
        a %= L

    return result
'''


'''python
def solve(a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    result.append(a % L)
    for i in range(n - 1):
        result.append((result[i] * result[i]) % L)
    return result
'''


'''python
def solve(n: int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    result.append(a % L)
    for i in range(n - 1):
        result.append((result[i] * result[i]) % L)
    return result
'''


'''python
def solve(a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    for i in range(n):
        result.append(a)
        a = a*a%L

    return result
'''


'''python
def solve(n: int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    for i in range(n):
        result.append(a)
        a = a*a%L

    return result
'''


'''python
def solve(n: int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    b = a
    for i in range(0, n):
        if i > 0:
            b = b*b
            b %= L
        b %= L
        result += [b]
    return result
'''


'''python
def solve(n: int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    for k in range(n):
        result.append((a ** (2 ** k)) % k)
    return result
'''


'''python
def solve(n: int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    for k in range(n):
        result.append((a ** (2 ** k)) % L)
    return result
'''


'''python
def solve(n: int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    for k in range(n):
        result.append(a)
        a = a * a
    return result
'''


'''python
def solve(n: int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    for k in range(n):
        result.append(a)
        a = (a * a) % L
    return result
'''


'''python
def solve(a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    n = 10**5
    act = a
    result.append(act)
    for i in range(1, n):
        act = pow(act, 2, L)
        result.append(act)
    return result
'''


'''python
def solve(a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    n = int(input())
    act = a
    result.append(act)
    for i in range(1, n):
        act = pow(act, 2, L)
        result.append(a)
    return result
'''


'''python
def solve(n:int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    act = a
    result.append(act)
    for i in range(1, n):
        act = pow(act, 2, L)
        result.append(a)
    return result
'''


'''python
def solve(n:int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    act = a
    result.append(act)
    for i in range(1, n-1):
        act = pow(a, 2, L)
        result.append(a)
    return result
'''


'''python
def solve(n:int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    act = a
    result.append(act)
    for i in range(1, n-1):
        act = pow(act, 2, L)
        result.append(a)
    return result
'''


'''python
def solve(n:int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    act = a
    result.append(act)
    for i in range(1, n-1):
        act = act**2 % L
        result.append(a)
    return result
'''


'''python
def solve(n:int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    act = a
    result.append(act)
    for i in range(1, n-1):
        act = act**2 % L
        result.append(act)
    return result
'''


'''python
def solve(n:int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    act = a
    result.append(act)
    for i in range(0, n-1):
        act = act**2 % L
        result.append(ac)
    return result
'''


'''python
def solve(n:int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    act = a
    result.append(act)
    for i in range(n-1):
        act = act**2 % L
        result.append(act)
    return result
'''


'''python
def solve(n: int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    result.append(a)
    for i in range(1,n):
        result.append(result[-1]**2%L)
    return result
'''


'''python
def solve(a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:

    result.append(a % L)
    for i in range(100000):
        last = result[-1]
        result.append(last*last % L)

    return result
'''


'''python
def solve(a, L):
    result = []
    result.append(a % L)
    for i in range(100000):
        last = result[-1]
        result.append(last*last % L)

    return result

solve(10, 13)
'''


'''python
def solve(n, a, L):
    result = []
    result.append(a % L)
    for i in range(n):
        last = result[-1]
        result.append(last*last % L)

    return result
'''


'''python
def solve(n, a, L):
    result = []
    result.append(a % L)
    for i in range(n-1):
        last = result[-1]
        result.append(last*last % L)

    return result
'''


'''python
def solve(n: int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    for i in range(n):
        result.append(a**(2**(i))%L)

    return result
'''


'''python
def solve(n: int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    result.append(a % L)
    for i in range(1, n):
        result.append(result[-1]**2 % L)

    return result
'''


'''python
def solve(a: int, L: int, n: int) -> list[int]:
    result: list[int] = []

    result.append(a)

    for i in range(1, n):
        result.append(pow(result[i - 1], 2, L))

    return result
'''


'''python
def solve(a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    for i in range(n):
        result.append(a):
        a = (a*a)%L;

    return result
'''


'''python
def solve(a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    for i in range(n):
        result.append(a)
        a = (a*a)%L

    return result
'''


'''python
def solve(n:int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    for i in range(n):
        result.append(a)
        a = (a*a)%L

    return result
'''


'''python
def solve(n: int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    for i in range(n):
        result.append(a**(2**i) % L)

    return result
'''


'''python
def solve(n: int, a: int, L: int) -> list[int]:
    result: list[int] = [a**(2**i) % L for i in range(n)]

    return result
'''


'''python
def solve(n: int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    result.append(a)

    if n == 1:
        return result

    for i in range(n-1):
        result.append(result[-1] * a**(2**i))

    return result
'''


'''python
def solve(n: int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    result.append(a)

    for i in range(n-1):
        result.append(result[-1] * a**(2**i) % L)

    return result
'''


'''python
def solve(n: int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    result.append(a)

    for i in range(n-1):
        result.append(result[-1] ** 2 % L)

    return result
'''


'''python
def solve(n: int, a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:

    return result
'''


'''python
def solve(a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    for k in range(n):
        result.append(a**(2**k) % L)

    return result
'''


'''python
def solve(a: int, L: int, n:int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    for k in range(n):
        result.append(a**(2**k) % L)

    return result
'''


'''python
def solve(a: int, L: int, n:int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    n = 10
    for k in range(n):
        result.append(a**(2**k) % L)

    return result
'''


'''python
def solve(a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    n = 1
    for k in range(n):
        result.append(a**(2**k) % L)

    return result
'''


'''python
def solve(a: int, L: int, n:int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    k = 0
    while True:
        if a >= L:
            a %= L
        result.append(a)

        a **= 2
        k += 1
        if k == n:
            break

    return result
'''


'''python
def solve(a: int, L: int) -> list[int]:
    result: list[int] = []
    # Write your code here:
    k = 0
    while True:
        if a >= L:
            a %= L
        result.append(a)

        a **= 2
        k += 1
        if k == n:
            break

    return result
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    test = 1
    while test % a != 0:
        test += L
    result = test // a
    return result
'''


'''python
def expansion_euclid(a: int, b: int) -> [int,int,int]:
    if b == 0:
        return a,1,0
    gcd,x1,y1 = expansion_euclid(b, a % b)
    x = x1
    y = x1 - (a // b) * y1
    return gcd,x,y
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    _,X,_ = expansion_euclid(a,L)
    return X % L
'''


'''python
def expansion_euclid(a: int, b: int) -> [int,int,int]:
    if b == 0:
        return a, 1, 0
    gcd, x1, y1 = expansion_euclid(b, a % b)
    x = y1
    y = x1 - (a // b) * y1
    return gcd, x, y
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    _, X, _ = expansion_euclid(a, L)
    return X % L
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0

    # 拡張ユークリッドの互除法
    def extended_gcd(x, y):
        if y == 0:
            return 1, 0
        s, t = extended_gcd(y, x % y)
        return t, s - (x // y) * t

    x, _ = extended_gcd(a, L)

    result = x % L
    return result
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    result = pow(a, -1, L)
    return result
'''


'''python
def extgcd(a, b):
    if b:
        d, y, x = extgcd(b, a % b)
        y -= (a // b) * x
        return d, x, y
    return a, 1, 0

def solve(a: int, L: int) -> int:
    _, x, _ = extgcd(a, L)

    return x % L
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    result=pow(a,-1,L)

    return result
'''


'''python
x, y = 0, 1

def gcdExtended(a, b):
    global x, y

    if (a == 0):
        x = 0
        y = 1
        return b

    gcd = gcdExtended(b % a, a)
    x1 = x
    y1 = y

    x = y1 - (b // a) * x1
    y = x1

    return gcd

def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    g = gcdExtended(A, M)
    if (g != 1):
        print("Inverse doesn't exist")
    else:
        res = (x % M + M) % M
    g = gcdExtended(A, M)
    result = (x % M + M) % M
    return result
'''


'''python
x, y = 0, 1
def gcdExtended(a, b):
    global x, y

    if a == 0:
        x = 0
        y = 1
        return b
    gcd = gcdExtended(b % a, a)
    x1 = x
    y1 = y

    x = y1 - (b // a) * x1
    y = x1

    return gcd

def solve(a: int, L: int) -> int:
    global x, y
    g = gcdExtended(a, L)
    if g != 1:
        return -1
    result = (x % L + L) % L
    return result
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    _,X,_ = extended_euclid(a,L)
    return X % L
def extended_euclid(a: int, b: int) -> tuple[int,int,int]:
    if b == 0:
        return a,1,0
    gcd,x1,y1 = extended_euclid(b,a%b)
    x = y1
    y = x1 - (a // b) * y1
    return gcd,x,y
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    result = pow(a, -1, L)

    return result
'''


'''python
def extended_gcd(a, b):
    if a == 0:
        return b, 0, 1
    else:
        g, x, y = extended_gcd(b % a, a)
        return g, y - (b // a) * x, x

def solve(a: int, L: int) -> int:
    g, x, y = extended_gcd(a, L)
    if g != 1:
        return None  # Modular inverse doesn't exist if a and L are not coprime
    else:
        return x % L

# Example usage:
a = 3
L = 11
print(solve(a, L))  # Output should be 4, since 3 * 4 mod 11 = 1
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    p = 0
    while True:
        if (p*L + 1) % a == 0:
            result = (p*L + 1) // a
            break
        p += 1

    return result
'''


'''python
def solve(a: int, L: int) -> int:
    return pow(a, -1, L)
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    result = pow(a,calculate_totient(N)-1,L)

    return result

def find_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5) + 1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:  # 同じ約数を二重に追加しない
                divisors.append(n // i)
    return sorted(divisors)

def calculate_totient(N):
    if N == 1:
        print(1)
    else:
        N_factor = find_divisors(N)[1:]
        totient = N
        while N_factor:
            totient = (totient*(N_factor[0]-1))//N_factor[0]
            N_factor = [k for k in N_factor if k % N_factor[0] != 0]
    return totient
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    result = pow(a,calculate_totient(L)-1,L)

    return result

def find_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5) + 1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:  # 同じ約数を二重に追加しない
                divisors.append(n // i)
    return sorted(divisors)

def calculate_totient(N):
    if N == 1:
        print(1)
    else:
        N_factor = find_divisors(N)[1:]
        totient = N
        while N_factor:
            totient = (totient*(N_factor[0]-1))//N_factor[0]
            N_factor = [k for k in N_factor if k % N_factor[0] != 0]
    return totient
'''


'''python
def solve(a: int, L: int) -> int:
    return pow(a, calculate_totient(L) - 1, L)

def calculate_totient(n: int) -> int:
    result = n
    p = 2
    while p * p <= n:
        if n % p == 0:
            while n % p == 0:
                n //= p
            result -= result // p  # φ(n) *= (1 - 1/p)
        p += 1
    if n > 1:
        result -= result // n
    return result
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    result = pow(a,calculate_totient(L)-1,L)

    return result

def find_prime_factors(n):
    factors = []
    is_prime = [True] * (int(n**0.5) + 1)
    is_prime[0:2] = [False,False]
    for i in range(int(n**0.5) + 1):
        if is_prime[i]:
            for j in range(2*i,int(n**0.5) + 1,i):
                is_prime[j] = False
            if n % i == 0:
                factors.append(i)
                while n % i == 0:
    	              n //= i
    if n > 1:
        factors.append(n)
    return factors

def calculate_totient(N):
    if N == 1:
        print(1)
    else:
        prime_factors = find_prime_factors(N)
        totient = N
        for p in prime_factors:
            totient -= totient//p
    return totient
'''


'''python
def extended_euclidean(a: int, b: int) -> tuple[int, int, int]:
    # when b == 0:
    if b == 0:
        return a, 1, 0

    # recursive step
    gcd, x1, y1 = extended_euclidean(b, a % b)

    # update x and y
    x = y1
    y = x1 - (a // b) * y1

    return gcd, x, y

def solve(a: int, L: int) -> int:
    _, x, _ = extended_euclidean(a, L)

    return x % L
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:

    def egcd(a: int, b: int):
        if b == 0:
            return (a, 1, 0)
        g, x, y = egcd(b, a % b)
        return (g, y, x - (a // b) * y)

    # a と L は互いに素なので gcd(a, L) = 1
    g, x, _ = egcd(a, L)
    # xが a の逆元 (mod L) であるが、負の場合もあるので正の値に変換
    result = x % L

    return result
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:

    def extgcd(a,b):
	  d = a
	  if b != 0:
	    d,(y,x) = extgcd(b,a % b)
	    y -= (a//b) * x
	  else:
	    x = 1
	    y = 0
	  return d,(x,y)

    _,(v,_) = extgcd(a,L)
    v = (v + L) % L
    result = v

    return result
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:

    def extgcd(a,b):
      d = a
      if b != 0:
      	d,(y,x) = extgcd(b,a % b)
      	y -= (a//b) * x
      else:
      	x = 1
      	y = 0
      return d,(x,y)

    _,(v,_) = extgcd(a,L)
    v = (v + L) % L
    result = v
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:

    import sys
    sys.setrecursionlimit(10000)

    def extgcd(a,b):
      d = a
      if b != 0:
      	d,(y,x) = extgcd(b,a % b)
      	y -= (a//b) * x
      else:
      	x = 1
      	y = 0
      return d,(x,y)

    _,(v,_) = extgcd(a,L)
    v = (v + L) % L
    result = v

    return result
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:

    # copied from https://qiita.com/akebono-san/items/f00c0db99342a8d68e5d :pray:
    a,b = a,L
    x, y, u, v = 1, 0, 0, 1
    while b:
        k = a // b
        x -= k * u
        y -= k * v
        x, u = u, x
        y, v = v, y
        a, b = b, a % b

    x = (x + L) % L
    result = x

    return result
'''


'''python
def solve(a: int, L: int) -> int:
    # Write your code here:
    for i in range(L - 1):
        if (a ** i) % L == 1:
            return i - 1
'''


'''python
def solve(a: int, L: int) -> int:
    # Write your code here:
    for i in range(1, L):
        if (a ** i) % L == 1:
            return a ** (i - 1) % L
'''


'''python
def extended_gcd(a, b):
    if b == 0:
        return a, 1, 0
    gcd, x1, y1 = extended_gcd(b, a % b)
    x = y1
    y = x1 - (a // b) * y1
    return gcd, x, y

def mod_inverse(a, L):
    gcd, x, _ = extended_gcd(a, L)
    if gcd != 1:
        raise ValueError()
    return x % L
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    return pow(a, -1, L)
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    m0, m1 = L, a
    y0, y1 = 0, 1

    while m1:
        m0, m1 = m1, m0 % m1
        y0, y1 = y1, y0 - y1 * (m0 // m1)

    if y0 < 0:
        y0 += L // m0

    result = y0
    return result
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    def extended_gcd(x, y):
        if y == 0:
            return x, 1, 0
        gcd, x1, y1 = extended_gcd(y, x % y)
        return gcd, y1, x1 - (x // y) * y1

    # a と L の最大公約数が 1 であれば逆元が存在
    gcd, x, y = extended_gcd(a, L)

    result = x % L
    return result
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:

    result = pow(a -1, L)

    return result
'''


'''python
from math import *
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:

    result = math.pow(a -1, L)

    return result
'''


'''python
def extgcd(x, y):

    if y == 0:
        return (1, 0, x)
    else:
        s1, t1, g = extgcd(y, x % y)

        s = t1
        t = s1 - (x // y) * t1
        return (s, t, g)

def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:

    result = s%L
    s, t, g = extgcd(a, L)

    return result
'''


'''python
def extgcd(x, y):

    if y == 0:
        return (1, 0, x)
    else:
        s1, t1, g = extgcd(y, x % y)

        s = t1
        t = s1 - (x // y) * t1
        return (s, t, g)

def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:

    s, t, g = extgcd(a, L)

    result = s%L

    return result
'''


'''python
def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)

def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:

    if gcd(a, L) > 1:

        # modulo inverse does not exist
        return -1
    for X in range(1, L):
        if (((a % L) * (X % L)) % L == 1):
            return X
    return -1

    # return result
'''


'''python
x, y = 0, 1

def gcdExtended(a, b):
    global x, y

    # Base Case
    if (a == 0):
        x = 0
        y = 1
        return b

    # To store results of recursive call
    gcd = gcdExtended(b % a, a)
    x1 = x
    y1 = y

    # Update x and y using results of recursive
    # call
    x = y1 - (b // a) * x1
    y = x1

    return gcd

def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:

    g = gcdExtended(a, L)
    if (g != 1):
        result = -1

    else:
        result = (x % L + L) % L

    return result
'''


'''python
def solve(a: int, L: int) -> int:
    return pow(a, -1, L)
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    for b in range(L):
        if a*b % L == 1:
            return b
    #return result
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    for b in range(L):
        if a*b % L == 1:
            return b
    return result
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    return pow(a, -1, L)
    #return result
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    if L == 1:
        result = 0
    else:
        result = 1

    return result
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0

    i0, i = a, L
    j0, j = 1, 0
    while i != 0:
        q = i0 // i
        i0, i = i, i0 - q * i
        j0, j = j, j0 - q * j

    result = j0 % L

    return result
'''


'''python
def solve(a: int, L: int) -> list[int]:
    result: int = 0
    # Write your code here:
    result = 1
    l = L-2
    while(l > 0):
        if(l%2 == 1):
            result = (result*a)%L
        a  = (a*a)%L
        l = int(l/2)

    return result
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    for i in range(1, L):
        if (((a % L) * (a % L)) % L == 1):
            return i
    return result
'''


'''python
def extended_gcd(a, b):
    if a == 0:
        return (b, 0, 1)
    else:
        g, x, y = extended_gcd(b % a, a)
        return (g, y - (b // a) * x, x)

def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    g, x, y = extended_gcd(a, L)
    return x % m
'''


'''python
def extended_gcd(a, b):
    if a == 0:
        return (b, 0, 1)
    else:
        g, x, y = extended_gcd(b % a, a)
        return (g, y - (b // a) * x, x)

def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    g, x, y = extended_gcd(a, L)
    return x % L
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:

    return pow(a, -1, L)
'''


'''python
from math import pow

def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    result =pow(a,-1,L)
    return result
'''


'''python
def extGCD(a, b) :
    if b ==  0 :
        return a, 1, 0
    d, y, x = extGCD(b, a%b)
    y -= a//b * x
    return d, x, y

def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    d,x,y=extGCD(a,L)
    result =x
    if result<0:
        result+=L
    return result
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0

    def extended_gcd(a: int, b: int):
        if a == 0:
            return b, 0, 1
        gcd, x1, y1 = extended_gcd(b % a, a)
        x = y1 - (b // a) * x1
        y = x1
        return gcd, x, y

    gcd, x, y = extended_gcd(a, L)

    # Since a and L are coprime, gcd should be 1
    if gcd != 1:
        raise ValueError("a and L are not coprime")

    # x is the modular inverse, we need to ensure it's positive
    result = x % L

    return result
'''


'''python
# gcd(a, b)とax+by=gcd(a,b)を満たすx,yを返す
def euclidean(a, b):
    x = w = 1
    y = z = 0
    while b:
        q = a // b
        r = a % b

        x, y, z, w = z, w, x - q * z, y - q * w
        a, b = b, r

    return a, x, y

def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    _, x, _ = euclidean(a, L)
    result = x % L

    return result
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    for k in range(n):
        result = pow(a, 2**k, L)
        results.append(result)

    return result
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    def extended_gcd(a,b):
        gcd, x1, y1 = extended_gcd(b % a,a)
        x = y1 - (b // a) * x1
        y = x1
        return gcd, x, y

    gcd, x, _ = extended_gcd(a,L)
    if gcd != 1:
        raise ValueError("互いに素で無いため逆元が存在しない。")
    else result = x % L

    return result
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    def extended_gcd(a,b):
        if a == 0:
            return b,0,1
        gcd, x1, y1 = extended_gcd(b % a,a)
        x = y1 - (b // a) * x1
        y = x1
        return gcd, x, y

    gcd, x, _ = extended_gcd(a,L)
    if gcd != 1:
        raise ValueError("互いに素で無いため逆元が存在しない。")
    else:
        result = x % L

    return result
'''


'''python
def solve(a: int, L: int) -> int:
    x = 0
    L0 = L
    y = 0

    while (a > 1):
        q = a // L
        t = m
        m = a % m
        a = t
        t = y
        y = x - q * y
        x = t

    if (x < 0):
        x = x + L0

    return x
'''


'''python
def solve(a: int, L: int) -> int:
    x = 0
    L0 = L
    y = 0

    while (a > 1):
        q = a // L
        t = m
        L = a % L
        a = t
        t = y
        y = x - q * y
        x = t

    if (x < 0):
        x = x + L0

    return x
'''


'''python
def solve(a: int, L: int) -> int:
    x = 0
    L0 = L
    y = 0

    while (a > 1):
        q = a // L
        t = L
        L = a % L
        a = t
        t = y
        y = x - q * y
        x = t

    if (x < 0):
        x = x + L0

    return x
'''


'''python
def solve(a: int, L: int) -> int:
    x = 1
    L0 = L
    y = 0

    while (a > 1):
        q = a // L
        t = L
        L = a % L
        a = t
        t = y
        y = x - q * y
        x = t

    if (x < 0):
        x = x + L0

    return x
'''


'''python
def power(a,b,m):
    result = 1
    while b > 0:
        if b % 2 != 0:
            result = (result * a) % m
        b //= 2
        a = (a * a) % m

    return result

def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    result = power(a, L-2, L)
    return result
'''


'''python
def power(a,b,m):
    result = 1
    a %= m
    while b > 0:
        if b % 2 != 0:
            result = (result * a) % m
        b //= 2
        a = (a * a) % m
    result %= m
    return result

def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    result = power(a, L-2, L)
    return result
'''


'''python
def extended_euclidean(X,Y):
    if X<Y:
        b, a, GCD = extended_euclidean(Y,X)

    x = X
    y = Y
    a = d = 1
    b = c = 0

    while y>0:
        q = x//y
        r = x%y
        if r==0: break # GCD 구해짐
        x,y,a,b,c,d = y,r,c,d,a-q*c,b-q*d

    return c,d,y

def solve(a: int, L: int) -> int:
    result: int = 0
    x,y,GCD = extended_euclidean(a, L)
    result = (x+L*1000)%L
    return result
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    result = pow(a, -1, L)
    return result
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0

    result = pow(a, -1, L)

    return result
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    result = 1
    while True:
        if ((result * a) % L) == 1:
            break
        else:
            result = (result * a) % L

    return result
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    result = result = pow(a, -1, mod=L)

    return result
'''


'''python
def solve(a: int, L: int) -> int:
    result: int = 0
    # Write your code here:
    def extended_gcd(x: int, y: int):
        if y == 0:
            return (1, 0, x)
        x2, y2, g = extended_gcd(y, x % y)
        return (y2, x2 - (x // y) * y2, g)

    x, _, g = extended_gcd(a, L)
    result = x % L

    return result
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister
from math import pi, acos, sqrt, asin
from qiskit.circuit.library import XGate, ZGate, PhaseGate, CU1Gate

"""
You can apply oracle as follows:
qc.compose(o, inplace=True)

"""

def QFT(n: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    for i in range(n//2):
        qc.swap(i, n-i-1)
    for i in range(n):
        qc.h(i)
        for j in range(i+1, n):
            qc.append(CU1Gate(pi/2**(j-i)), [j, i])
    return qc

def B2(n: int, a: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    qc.compose(QFT(n), range(n), inplace=True)
    for i in range(n):
        qc.append(PhaseGate(2*pi*a*(1/2)**(n-i)), [i])
    qc.compose(QFT(n).inverse(), range(n), inplace=True)
    return qc

def B3(n: int, a: int) -> QuantumCircuit:
    k, c = QuantumRegister(n), QuantumRegister(1)
    qc = QuantumCircuit(k, c)
    # qc.x(n)

    qc.append(QFT(n).control(1), [n, *range(n)])
    for i in range(n):
        qc.append(PhaseGate(2*pi*a*(1/2)**(n-i)).control(1), [n, i])
    qc.append(QFT(n).inverse().control(1), [n, *range(n)])

    return qc.decompose(reps=2)

def B4(n: int, s: int, t: int) -> QuantumCircuit:
    qc = QuantumCircuit(n + 1)
    # Write your code here:
    qc.compose(B3(n, -t), range(n + 1), inplace=True)
    qc.x(n)
    qc.compose(B3(n, -s), range(n + 1), inplace=True)
    qc.x(n)

    return qc

def B5(n: int, a: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n + 1)
    a=L-a
    # Write your code here:
    qc.compose(B2(n+1, 2**n-a), range(n + 1), inplace=True)
    qc.compose(B4(n, 2**n-a, 2**n-a+L), range(n + 1), inplace=True)
    qc.x(n)
    qc.compose(B2(n+1, -2**n+L-a), range(n + 1), inplace=True)

    return qc

def solve(n: int, a: int, L: int) -> QuantumCircuit:
    x, y = QuantumRegister(n), QuantumRegister(n + 1)
    qc = QuantumCircuit(x, y)
    # Write your code here:
    for i in range(n):
        qc.compose(B5(n, a, L).control(1), [i] + list(range(n, n + n + 1)), inplace=True)
        a += a
        a %= L

    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister

def solve(n: int, a: int, L: int) -> QuantumCircuit:
    x = QuantumRegister(n)  # Register for x
    y = QuantumRegister(n + 1)  # Register for y (n + 1 qubits)
    qc = QuantumCircuit(x, y)

    # We will use a series of controlled additions to implement the oracle
    for x_value in range(0, L):
        # Calculate ax mod L
        ax_mod_L = (a * x_value) % L

        # Convert x_value to binary and apply controlled addition
        for i in range(n):
            if (x_value >> i) & 1:  # If the i-th bit of x_value is 1
                # We need to add ax_mod_L to y
                # We will add ax_mod_L to y using controlled operations
                for j in range(n + 1):
                    if (ax_mod_L >> j) & 1:  # If the j-th bit of ax_mod_L is 1
                        # Apply a controlled NOT gate to add the j-th bit of ax_mod_L to y
                        qc.cx(x[i], y[j])

    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister

def solve(n: int, a: int, L: int) -> QuantumCircuit:
    x, y = QuantumRegister(n), QuantumRegister(n + 1)
    qc = QuantumCircuit(x, y)
    # Write your code here:

    for i in range(x):
        if (a >> i) & 1:  # Check if the i-th bit of 'a' is 1
            for j in range(ny):
                oracle.append(CXGate(), [x + j, i])  # Controlled-X from y to x

    # Add the y register to the result (modular addition is handled implicitly by Qiskit)
    for i in range(y):
        oracle.append(CXGate(), [x + y + i, x + i])  # Controlled-X from output to x

    # Apply the modular reduction (mod L) if L < 2^n
    if L < 2**n:
        # Implement modular reduction using subtraction and conditional flips
        for i in range(n - 1, -1, -1):
            if (L >> i) & 1:  # Check if the i-th bit of L is 1
                for j in range(i):
                    oracle.append(CXGate(), [x + y + j, x + y + i])  # Controlled-X from lower bits to i-th bit

    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister

def solve(n: int, a: int, L: int) -> QuantumCircuit:
    # Create quantum registers for x and y
    x, y = QuantumRegister(n), QuantumRegister(n + 1)

    # Create quantum circuit
    qc = QuantumCircuit(x, y)

    # We need to implement: |x⟩|y⟩ → |x⟩|(y + ax) mod L⟩

    # For each bit position i in x register
    for i in range(n):
        # Control on x[i] being 1
        # If x[i] is 1, add (2^i * a) mod L to y
        controlled_value = (pow(2, i) * a) % L

        # Implement controlled modular addition
        # Use standard quantum addition circuits with modulo L
        # This typically involves quantum adders and modular reduction
        for j in range(n):
            if (controlled_value >> j) & 1:
                qc.cx(x[i], y[j])

    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library import QFT

def modular_addition(qc, x, y, a, L, n):
    """ Implements y -> (y + ax) mod L """
    for i in range(n):
        for j in range(n + 1):
            if (a >> i) & 1:
                qc.ccx(x[i], y[j], y[(j + (1 << i)) % (n + 1)])

    # Modulo L enforcement
    qc.append(QFT(n+1, do_swaps=False).inverse(), y)
    qc.x(y[n])
    qc.append(QFT(n+1, do_swaps=False), y)

    return qc

def solve(n: int, a: int, L: int) -> QuantumCircuit:
    x = QuantumRegister(n, name='x')
    y = QuantumRegister(n + 1, name='y')
    qc = QuantumCircuit(x, y)

    # Implement modular addition oracle
    modular_addition(qc, x, y, a, L, n)

    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister

def solve(n: int, a: int, L: int) -> QuantumCircuit:
    x = QuantumRegister(n, 'x')
    y = QuantumRegister(n + 1, 'y')
    qc = QuantumCircuit(x, y)

    # Apply controlled addition for each qubit in x
    for i in range(n):
        # Controlled addition of a * 2^i to y
        for j in range(n + 1):
            if (a * (1 << i)) & (1 << j):
                qc.cx(x[i], y[j])

    # Apply modulo L operation
    # Since L <= 2^n, we can use a comparison and subtraction approach
    # This is a simplified approach and may need refinement for specific cases
    # For a full implementation, additional qubits and gates would be needed

    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister

def solve(n: int, a: int, L: int) -> QuantumCircuit:
    # Create quantum registers for x and y
    x = QuantumRegister(n, 'x')
    y = QuantumRegister(n, 'y')

    # Create quantum circuit
    qc = QuantumCircuit(x, y)

    # We need to perform (y + ax) mod L
    # We can implement this using controlled additions

    # For each qubit i in x register
    for i in range(n):
        # If the i-th bit of x is 1, we add a*2^i to y (controlled addition)
        value = (a * (1 << i)) % L  # Calculate the value to add (mod L)

        # Break down value into binary for controlled additions
        for j in range(n):
            if value & (1 << j):
                qc.cx(x[i], y[j])

    # The modulo L operation is handled implicitly since:
    # 1. L <= 2^n (from constraints)
    # 2. We're already doing (a * 2^i) mod L in our addition

    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister

def solve(n: int, a: int, L: int) -> QuantumCircuit:
    # Create quantum registers for x and y
    x = QuantumRegister(n, 'x')
    y = QuantumRegister(n + 1, 'y')  # Note: n+1 qubits for y as per problem

    # Create quantum circuit
    qc = QuantumCircuit(x, y)

    # For each bit i in x
    for i in range(n):
        # For each bit j in y
        for j in range(n + 1):
            # Apply controlled addition based on the pattern:
            # If bit i in x is 1, we add corresponding value to y
            if (a * (1 << i)) & (1 << j):
                qc.cx(x[i], y[j])

    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister

def solve(n: int, a: int, L: int) -> QuantumCircuit:
    # Create quantum registers for x and y
    x = QuantumRegister(n, 'x')
    y = QuantumRegister(n + 1, 'y')

    # Create quantum circuit
    qc = QuantumCircuit(x, y)

    # Apply controlled addition for each qubit in x
    for i in range(n):
        # Controlled addition of a * 2^i to y
        for j in range(n + 1):
            if (a * (1 << i)) & (1 << j):
                if j > 0:  # Only apply when j > 0 as per example
                    qc.cx(x[i], y[j])

    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister

def solve(n: int, a: int, L: int) -> QuantumCircuit:
    # Create quantum registers for x and y
    x = QuantumRegister(n, 'x')
    y = QuantumRegister(n + 1, 'y')  # n+1 qubits for y register

    # Create quantum circuit
    qc = QuantumCircuit(x, y)

    # Apply controlled addition for each qubit in x
    for i in range(n):
        for j in range(n + 1):
            # Following exactly the condition from the example
            if (a * (1 << i)) & (1 << j):
                qc.cx(x[i], y[j])

    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister

def solve(n: int, a: int, L: int) -> QuantumCircuit:
    # Initialize registers
    x = QuantumRegister(n, 'x')
    y = QuantumRegister(n, 'y')  # Note: Problem shows n qubits for y
    qc = QuantumCircuit(x, y)

    # Controlled addition of ax mod L to y
    # The key is to apply controlled-X gates based on the binary representation
    # of (a * x) mod L

    # For each control qubit in x
    for i in range(n):
        # For each target qubit in y
        for j in range(n):
            # The condition from example: if this bit position should flip
            if (a * (1 << i)) & (1 << j):
                # Apply controlled-NOT from x[i] to y[j]
                qc.cx(x[i], y[j])

    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister

def solve(n: int, a: int, L: int) -> QuantumCircuit:
    """
    Creates a quantum circuit that performs modular multiplication: |x⟩|y⟩ → |x⟩|y ⊕ (ax mod L)⟩

    Args:
        n (int): Number of qubits in each register
        a (int): Multiplication factor
        L (int): Modulus

    Returns:
        QuantumCircuit: Circuit implementing the modular multiplication
    """
    # Initialize registers
    x = QuantumRegister(n, 'x')
    y = QuantumRegister(n, 'y')
    qc = QuantumCircuit(x, y)

    # For each possible value of x
    for x_val in range(1 << n):
        # Calculate (a * x_val) mod L
        result = (a * x_val) % L

        # For each target qubit in y
        for j in range(n):
            # If this bit should be flipped for this x_val
            if result & (1 << j):
                # Create control pattern for this x_val
                for i in range(n):
                    # Apply X or CX gates based on x_val bits
                    if x_val & (1 << i):
                        qc.cx(x[i], y[j])
                    else:
                        # If control bit should be 0, add X gates before and after
                        qc.x(x[i])
                        qc.cx(x[i], y[j])
                        qc.x(x[i])

    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister

def solve(n: int, a: int, L: int) -> QuantumCircuit:
    """
    Creates a quantum circuit that performs modular multiplication: |x⟩|y⟩ → |x⟩|y ⊕ (ax mod L)⟩

    Args:
        n (int): Number of qubits in each register
        a (int): Multiplication factor
        L (int): Modulus

    Returns:
        QuantumCircuit: Circuit implementing the modular multiplication
    """
    # Initialize registers
    x = QuantumRegister(n, 'x')
    y = QuantumRegister(n, 'y')
    qc = QuantumCircuit(x, y)

    # Create table of all possible values and their modular products
    for x_val in range(1 << n):
        result = (a * x_val) % L

        # For each bit in result
        for j in range(n):
            if result & (1 << j):
                # Create control pattern
                controls = []
                neg_controls = []

                # Determine which qubits should be controlled on 0 vs 1
                for i in range(n):
                    if x_val & (1 << i):
                        controls.append(i)
                    else:
                        neg_controls.append(i)

                # Apply X gates before controlled operation
                for i in neg_controls:
                    qc.x(x[i])

                # Apply multi-controlled X gate
                if len(controls + neg_controls) > 0:
                    for control in controls + neg_controls:
                        qc.cx(x[control], y[j])

                # Restore X gates after controlled operation
                for i in neg_controls:
                    qc.x(x[i])

    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister

def solve(n: int, a: int, L: int) -> QuantumCircuit:
    x, y = QuantumRegister(n), QuantumRegister(n + 1)
    qc = QuantumCircuit(x, y)
    # Write your code here:
    for i in range(n):
        for j in range(n+1):
            if (a >> i) & 1:
                qc.cx(x[i], y[j])  # CNOTゲートでx[i]に基づいてy[j]に操作を行う

    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library import RYGate
import numpy as np
import math

def qft(n):
    qc = QuantumCircuit(n)

    thetas = []
    for k in range(0, 1 + n):
        thetas.append(2 * math.pi / (2**k))

    for idx in range(0, n):
        qc.h(n - 1 - idx)
        for jdx in range(idx + 1, n):
            thetaidx = jdx - idx + 1
            qc.cp(thetas[thetaidx], n - 1 - jdx, n - 1 - idx)

    for idx in range(0, n // 2):
        qc.swap(idx, n - idx - 1)

    return qc

def add(n: int, a: int) -> QuantumCircuit:
    k = QuantumRegister(n)
    qc = QuantumCircuit(k)
    # Write your code here:

    qc.compose(qft(n), inplace=True)

    for idx in range(n):
        theta = 2 * a * math.pi * (2**idx) / (2**n)
        qc.p(theta, k[idx])

    qc.compose(qft(n).inverse(), inplace=True)

    return qc

def controlled_add(n: int, a: int, control_count: int) -> QuantumCircuit:
    k, c = QuantumRegister(n), QuantumRegister(control_count)
    qc = QuantumCircuit(k, c)
    # Write your code here:

    qc.compose(qft(n), inplace=True)

    for idx in range(n):
        theta = 2 * a * math.pi * (2**idx) / (2**n)
        qc.mcp(theta, c, k[idx])

    qc.compose(qft(n).inverse(), inplace=True)

    return qc

def oracle_less(bitcount: int, n: int) -> QuantumCircuit:
    regin, regout = QuantumRegister(bitcount), QuantumRegister(1)
    qc = QuantumCircuit(regin, regout)

    if n >= 2**bitcount:
        qc.x(regout)
        return qc

    bitrep = bin(n)[2:].zfill(bitcount)[::-1]
    masks = []

    for idx in range(bitcount):
        if bitrep[idx] == "1":
            mask = ("0" + bitrep[idx + 1 :]).rjust(bitcount, "*")
            masks.append(mask)

    flipped = [False] * bitcount
    for mask in masks:
        controls = []
        for idx in range(bitcount):
            if mask[idx] == "*":
                continue

            controls.append(regin[idx])
            if (mask[idx] == "0") != (flipped[idx]):
                flipped[idx] = not flipped[idx]
                qc.x(regin[idx])

        if len(controls) != 0:
            qc.mcx(controls, regout)

    for idx in range(bitcount):
        if flipped[idx]:
            qc.x(regin[idx])

    return qc

def controlled_oracle_less(bitcount: int, n: int, control_count: int) -> QuantumCircuit:
    regin, regout = QuantumRegister(bitcount), QuantumRegister(1)
    control = QuantumRegister(control_count)
    qc = QuantumCircuit(regin, regout, control)

    if n >= 2**bitcount:
        qc.mcx(control, regout)
        return qc

    bitrep = bin(n)[2:].zfill(bitcount)[::-1]
    masks = []

    for idx in range(bitcount):
        if bitrep[idx] == "1":
            mask = ("0" + bitrep[idx + 1 :]).rjust(bitcount, "*")
            masks.append(mask)

    flipped = [False] * bitcount
    for mask in masks:
        regin_controls = []
        for idx in range(bitcount):
            if mask[idx] == "*":
                continue

            regin_controls.append(regin[idx])
            if (mask[idx] == "0") != (flipped[idx]):
                flipped[idx] = not flipped[idx]
                qc.mcx(control, regin[idx])

        if len(regin_controls) != 0:
            qc.mcx([*regin_controls, *control], regout)

    for idx in range(bitcount):
        if flipped[idx]:
            qc.x(regin[idx])

    return qc

def cmodadd(n: int, a: int, L: int) -> QuantumCircuit:
    """in(n+1), control, anc1, anc2, anc3"""
    regin = QuantumRegister(n + 1)
    control = QuantumRegister(1)
    qc = QuantumCircuit(regin, control)
    # Write your code here:

    anc_range1 = QuantumRegister(1)
    anc_range2 = QuantumRegister(1)
    anc_range3 = QuantumRegister(1)
    qc.add_register(anc_range1)
    qc.add_register(anc_range2)
    qc.add_register(anc_range3)

    qc.cx(control, anc_range1)
    qc.compose(
        controlled_oracle_less(n + 1, L, 1),
        [*regin, *anc_range2, *control],
        inplace=True,
    )
    qc.compose(
        controlled_oracle_less(n + 1, L - a, 1),
        [*regin, *anc_range1, *control],
        inplace=True,
    )
    qc.mcx([*control, anc_range1, anc_range2], anc_range3)

    qc.compose(controlled_add(n + 1, a, 1), [*regin, *control], inplace=True)
    qc.compose(
        controlled_add(n + 1, -L, 2), [*regin, *anc_range3, *control], inplace=True
    )
    qc.mcx([anc_range1, anc_range2, *control], anc_range3)

    qc.cx(control, anc_range2)
    qc.cx(control, regin[-1])
    qc.mcx([regin[-1], *anc_range2, *control], anc_range3)
    qc.cx(control, regin[-1])
    qc.compose(
        controlled_add(n + 1, L, 2), [*regin, *anc_range3, *control], inplace=True
    )

    qc.compose(
        controlled_oracle_less(n + 1, 2 ** (n + 1) + 1 - L, 1),
        [*regin, *anc_range3, *control],
        inplace=True,
    )
    qc.compose(controlled_oracle_less(n + 1, L, 1), [*regin, *anc_range3,*control], inplace=True)

    qc.cx(control, anc_range2)
    qc.compose(controlled_oracle_less(n + 1, L, 1), [*regin, *anc_range2,*control], inplace=True)

    qc.compose(controlled_oracle_less(n + 1, L, 1), [*regin, *anc_range1,*control], inplace=True)
    qc.compose(controlled_oracle_less(n + 1, a, 1), [*regin, *anc_range1,*control], inplace=True)
    qc.cx(control, anc_range1)

    return qc

def modfma(n: int, a: int, L: int) -> QuantumCircuit:
    x, y = QuantumRegister(n), QuantumRegister(n + 1)
    qc = QuantumCircuit(x, y)
    # Write your code here:

    ancs = QuantumRegister(3)
    qc.add_register(ancs)

    for idx in range(n):
        add = pow(a, 2**idx, L)
        qc.compose(cmodadd(n, add, L), [*y, x[idx], *ancs], inplace=True)

    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library import RYGate
import numpy as np
import math

def qft(n):
    qc = QuantumCircuit(n)

    thetas = []
    for k in range(0, 1 + n):
        thetas.append(2 * math.pi / (2**k))

    for idx in range(0, n):
        qc.h(n - 1 - idx)
        for jdx in range(idx + 1, n):
            thetaidx = jdx - idx + 1
            qc.cp(thetas[thetaidx], n - 1 - jdx, n - 1 - idx)

    for idx in range(0, n // 2):
        qc.swap(idx, n - idx - 1)

    return qc

def add(n: int, a: int) -> QuantumCircuit:
    k = QuantumRegister(n)
    qc = QuantumCircuit(k)
    # Write your code here:

    qc.compose(qft(n), inplace=True)

    for idx in range(n):
        theta = 2 * a * math.pi * (2**idx) / (2**n)
        qc.p(theta, k[idx])

    qc.compose(qft(n).inverse(), inplace=True)

    return qc

def controlled_add(n: int, a: int, control_count: int) -> QuantumCircuit:
    k, c = QuantumRegister(n), QuantumRegister(control_count)
    qc = QuantumCircuit(k, c)
    # Write your code here:

    qc.compose(qft(n), inplace=True)

    for idx in range(n):
        theta = 2 * a * math.pi * (2**idx) / (2**n)
        qc.mcp(theta, c, k[idx])

    qc.compose(qft(n).inverse(), inplace=True)

    return qc

def oracle_less(bitcount: int, n: int) -> QuantumCircuit:
    regin, regout = QuantumRegister(bitcount), QuantumRegister(1)
    qc = QuantumCircuit(regin, regout)

    if n >= 2**bitcount:
        qc.x(regout)
        return qc

    bitrep = bin(n)[2:].zfill(bitcount)[::-1]
    masks = []

    for idx in range(bitcount):
        if bitrep[idx] == "1":
            mask = ("0" + bitrep[idx + 1 :]).rjust(bitcount, "*")
            masks.append(mask)

    flipped = [False] * bitcount
    for mask in masks:
        controls = []
        for idx in range(bitcount):
            if mask[idx] == "*":
                continue

            controls.append(regin[idx])
            if (mask[idx] == "0") != (flipped[idx]):
                flipped[idx] = not flipped[idx]
                qc.x(regin[idx])

        if len(controls) != 0:
            qc.mcx(controls, regout)

    for idx in range(bitcount):
        if flipped[idx]:
            qc.x(regin[idx])

    return qc

def controlled_oracle_less(bitcount: int, n: int, control_count: int) -> QuantumCircuit:
    regin, regout = QuantumRegister(bitcount), QuantumRegister(1)
    control = QuantumRegister(control_count)
    qc = QuantumCircuit(regin, regout, control)

    if n >= 2**bitcount:
        qc.mcx(control, regout)
        return qc

    bitrep = bin(n)[2:].zfill(bitcount)[::-1]
    masks = []

    for idx in range(bitcount):
        if bitrep[idx] == "1":
            mask = ("0" + bitrep[idx + 1 :]).rjust(bitcount, "*")
            masks.append(mask)

    flipped = [False] * bitcount
    for mask in masks:
        regin_controls = []
        for idx in range(bitcount):
            if mask[idx] == "*":
                continue

            regin_controls.append(regin[idx])
            if (mask[idx] == "0") != (flipped[idx]):
                flipped[idx] = not flipped[idx]
                qc.mcx(control, regin[idx])

        if len(regin_controls) != 0:
            qc.mcx([*regin_controls, *control], regout)

    for idx in range(bitcount):
        if flipped[idx]:
            qc.mcx(control, regin[idx])

    return qc

def modadd(n: int, a: int, L: int) -> QuantumCircuit:
    regin = QuantumRegister(n + 1)
    qc = QuantumCircuit(regin)
    # Write your code here:

    anc_range1 = QuantumRegister(1)
    anc_range2 = QuantumRegister(1)
    anc_range3 = QuantumRegister(1)
    qc.add_register(anc_range1)
    qc.add_register(anc_range2)
    qc.add_register(anc_range3)

    qc.x(anc_range1)
    qc.compose(oracle_less(n + 1, L), [*regin, *anc_range2], inplace=True)
    qc.compose(oracle_less(n + 1, L - a), [*regin, *anc_range1], inplace=True)
    qc.ccx(anc_range1, anc_range2, anc_range3)

    qc.compose(add(n + 1, a), inplace=True)
    qc.compose(controlled_add(n + 1, -L, 1), [*regin, *anc_range3], inplace=True)
    qc.ccx(anc_range1, anc_range2, anc_range3)

    qc.x(anc_range2)
    qc.x(regin[-1])
    qc.ccx(regin[-1], anc_range2, anc_range3)
    qc.x(regin[-1])
    qc.compose(controlled_add(n + 1, L, 1), [*regin, *anc_range3], inplace=True)

    qc.compose(
        oracle_less(n + 1, 2 ** (n + 1) + 1 - L), [*regin, *anc_range3], inplace=True
    )
    qc.compose(oracle_less(n + 1, L), [*regin, *anc_range3], inplace=True)

    qc.x(anc_range2)
    qc.compose(oracle_less(n + 1, L), [*regin, *anc_range2], inplace=True)

    qc.compose(oracle_less(n + 1, L), [*regin, *anc_range1], inplace=True)
    qc.compose(oracle_less(n + 1, a), [*regin, *anc_range1], inplace=True)
    qc.x(anc_range1)

    return qc

def cmodadd(n: int, a: int, L: int) -> QuantumCircuit:
    """in(n+1), control, anc1, anc2, anc3"""
    regin = QuantumRegister(n + 1)
    control = QuantumRegister(1)
    qc = QuantumCircuit(regin, control)
    # Write your code here:

    anc_range1 = QuantumRegister(1)
    anc_range2 = QuantumRegister(1)
    anc_range3 = QuantumRegister(1)
    qc.add_register(anc_range1)
    qc.add_register(anc_range2)
    qc.add_register(anc_range3)

    qc.cx(control, anc_range1)
    qc.compose(
        controlled_oracle_less(n + 1, L, 1),
        [*regin, *anc_range2, *control],
        inplace=True,
    )
    qc.compose(
        controlled_oracle_less(n + 1, L - a, 1),
        [*regin, *anc_range1, *control],
        inplace=True,
    )
    qc.mcx([*control, anc_range1, anc_range2], anc_range3)

    qc.compose(controlled_add(n + 1, a, 1), [*regin, *control], inplace=True)
    qc.compose(
        controlled_add(n + 1, -L, 2), [*regin, *anc_range3, *control], inplace=True
    )
    qc.mcx([anc_range1, anc_range2, *control], anc_range3)

    qc.cx(control, anc_range2)
    qc.cx(control, regin[-1])
    qc.mcx([regin[-1], *anc_range2, *control], anc_range3)
    qc.cx(control, regin[-1])
    qc.compose(
        controlled_add(n + 1, L, 2), [*regin, *anc_range3, *control], inplace=True
    )

    qc.compose(
        controlled_oracle_less(n + 1, 2 ** (n + 1) + 1 - L, 1),
        [*regin, *anc_range3, *control],
        inplace=True,
    )
    qc.compose(
        controlled_oracle_less(n + 1, L, 1),
        [*regin, *anc_range3, *control],
        inplace=True,
    )

    qc.cx(control, anc_range2)
    qc.compose(
        controlled_oracle_less(n + 1, L, 1),
        [*regin, *anc_range2, *control],
        inplace=True,
    )

    qc.compose(
        controlled_oracle_less(n + 1, L, 1),
        [*regin, *anc_range1, *control],
        inplace=True,
    )
    qc.compose(
        controlled_oracle_less(n + 1, a, 1),
        [*regin, *anc_range1, *control],
        inplace=True,
    )
    qc.cx(control, anc_range1)

    return qc

def modfma(n: int, a: int, L: int) -> QuantumCircuit:
    x, y = QuantumRegister(n), QuantumRegister(n + 1)
    qc = QuantumCircuit(x, y)
    # Write your code here:

    ancs = QuantumRegister(3)
    qc.add_register(ancs)

    for idx in range(n):
        add = pow(a, 2**idx, L)
        qc.compose(cmodadd(n, add, L), [*y, x[idx], *ancs], inplace=True)

    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library import RYGate
import numpy as np
import math

def qft(n):
    qc = QuantumCircuit(n)

    thetas = []
    for k in range(0, 1 + n):
        thetas.append(2 * math.pi / (2**k))

    for idx in range(0, n):
        qc.h(n - 1 - idx)
        for jdx in range(idx + 1, n):
            thetaidx = jdx - idx + 1
            qc.cp(thetas[thetaidx], n - 1 - jdx, n - 1 - idx)

    for idx in range(0, n // 2):
        qc.swap(idx, n - idx - 1)

    return qc

def add(n: int, a: int) -> QuantumCircuit:
    k = QuantumRegister(n)
    qc = QuantumCircuit(k)
    # Write your code here:

    qc.compose(qft(n), inplace=True)

    for idx in range(n):
        theta = 2 * a * math.pi * (2**idx) / (2**n)
        qc.p(theta, k[idx])

    qc.compose(qft(n).inverse(), inplace=True)

    return qc

def controlled_add(n: int, a: int, control_count: int) -> QuantumCircuit:
    k, c = QuantumRegister(n), QuantumRegister(control_count)
    qc = QuantumCircuit(k, c)
    # Write your code here:

    qc.compose(qft(n), inplace=True)

    for idx in range(n):
        theta = 2 * a * math.pi * (2**idx) / (2**n)
        qc.mcp(theta, c, k[idx])

    qc.compose(qft(n).inverse(), inplace=True)

    return qc

def oracle_less(bitcount: int, n: int) -> QuantumCircuit:
    regin, regout = QuantumRegister(bitcount), QuantumRegister(1)
    qc = QuantumCircuit(regin, regout)

    if n >= 2**bitcount:
        qc.x(regout)
        return qc

    bitrep = bin(n)[2:].zfill(bitcount)[::-1]
    masks = []

    for idx in range(bitcount):
        if bitrep[idx] == "1":
            mask = ("0" + bitrep[idx + 1 :]).rjust(bitcount, "*")
            masks.append(mask)

    flipped = [False] * bitcount
    for mask in masks:
        controls = []
        for idx in range(bitcount):
            if mask[idx] == "*":
                continue

            controls.append(regin[idx])
            if (mask[idx] == "0") != (flipped[idx]):
                flipped[idx] = not flipped[idx]
                qc.x(regin[idx])

        if len(controls) != 0:
            qc.mcx(controls, regout)

    for idx in range(bitcount):
        if flipped[idx]:
            qc.x(regin[idx])

    return qc

def controlled_oracle_less(bitcount: int, n: int, control_count: int) -> QuantumCircuit:
    regin, regout = QuantumRegister(bitcount), QuantumRegister(1)
    control = QuantumRegister(control_count)
    qc = QuantumCircuit(regin, regout, control)

    if n >= 2**bitcount:
        qc.mcx(control, regout)
        return qc

    bitrep = bin(n)[2:].zfill(bitcount)[::-1]
    masks = []

    for idx in range(bitcount):
        if bitrep[idx] == "1":
            mask = ("0" + bitrep[idx + 1 :]).rjust(bitcount, "*")
            masks.append(mask)

    flipped = [False] * bitcount
    for mask in masks:
        regin_controls = []
        for idx in range(bitcount):
            if mask[idx] == "*":
                continue

            regin_controls.append(regin[idx])
            if (mask[idx] == "0") != (flipped[idx]):
                flipped[idx] = not flipped[idx]
                qc.mcx(control, regin[idx])

        if len(regin_controls) != 0:
            qc.mcx([*regin_controls, *control], regout)

    for idx in range(bitcount):
        if flipped[idx]:
            qc.mcx(control, regin[idx])

    return qc

def modadd(n: int, a: int, L: int) -> QuantumCircuit:
    regin = QuantumRegister(n + 1)
    qc = QuantumCircuit(regin)
    # Write your code here:

    anc_range1 = QuantumRegister(1)
    anc_range2 = QuantumRegister(1)
    anc_range3 = QuantumRegister(1)
    qc.add_register(anc_range1)
    qc.add_register(anc_range2)
    qc.add_register(anc_range3)

    qc.x(anc_range1)
    qc.compose(oracle_less(n + 1, L), [*regin, *anc_range2], inplace=True)
    qc.compose(oracle_less(n + 1, L - a), [*regin, *anc_range1], inplace=True)
    qc.ccx(anc_range1, anc_range2, anc_range3)

    qc.compose(add(n + 1, a), inplace=True)
    qc.compose(controlled_add(n + 1, -L, 1), [*regin, *anc_range3], inplace=True)
    qc.ccx(anc_range1, anc_range2, anc_range3)

    qc.x(anc_range2)
    qc.x(regin[-1])
    qc.ccx(regin[-1], anc_range2, anc_range3)
    qc.x(regin[-1])
    qc.compose(controlled_add(n + 1, L, 1), [*regin, *anc_range3], inplace=True)

    qc.compose(
        oracle_less(n + 1, 2 ** (n + 1) + 1 - L), [*regin, *anc_range3], inplace=True
    )
    qc.compose(oracle_less(n + 1, L), [*regin, *anc_range3], inplace=True)

    qc.x(anc_range2)
    qc.compose(oracle_less(n + 1, L), [*regin, *anc_range2], inplace=True)

    qc.compose(oracle_less(n + 1, L), [*regin, *anc_range1], inplace=True)
    qc.compose(oracle_less(n + 1, a), [*regin, *anc_range1], inplace=True)
    qc.x(anc_range1)

    return qc

def cmodadd(n: int, a: int, L: int) -> QuantumCircuit:
    """in(n+1), control, anc1, anc2, anc3"""
    regin = QuantumRegister(n + 1)
    control = QuantumRegister(1)
    qc = QuantumCircuit(regin, control)
    # Write your code here:

    anc_range1 = QuantumRegister(1)
    anc_range2 = QuantumRegister(1)
    anc_range3 = QuantumRegister(1)
    qc.add_register(anc_range1)
    qc.add_register(anc_range2)
    qc.add_register(anc_range3)

    qc.cx(control, anc_range1)
    qc.compose(
        controlled_oracle_less(n + 1, L, 1),
        [*regin, *anc_range2, *control],
        inplace=True,
    )
    qc.compose(
        controlled_oracle_less(n + 1, L - a, 1),
        [*regin, *anc_range1, *control],
        inplace=True,
    )
    qc.mcx([*control, anc_range1, anc_range2], anc_range3)

    qc.compose(controlled_add(n + 1, a, 1), [*regin, *control], inplace=True)
    qc.compose(
        controlled_add(n + 1, -L, 2), [*regin, *anc_range3, *control], inplace=True
    )
    qc.mcx([anc_range1, anc_range2, *control], anc_range3)

    qc.cx(control, anc_range2)
    qc.cx(control, regin[-1])
    qc.mcx([regin[-1], *anc_range2, *control], anc_range3)
    qc.cx(control, regin[-1])
    qc.compose(
        controlled_add(n + 1, L, 2), [*regin, *anc_range3, *control], inplace=True
    )

    qc.compose(
        controlled_oracle_less(n + 1, 2 ** (n + 1) + 1 - L, 1),
        [*regin, *anc_range3, *control],
        inplace=True,
    )
    qc.compose(
        controlled_oracle_less(n + 1, L, 1),
        [*regin, *anc_range3, *control],
        inplace=True,
    )

    qc.cx(control, anc_range2)
    qc.compose(
        controlled_oracle_less(n + 1, L, 1),
        [*regin, *anc_range2, *control],
        inplace=True,
    )

    qc.compose(
        controlled_oracle_less(n + 1, L, 1),
        [*regin, *anc_range1, *control],
        inplace=True,
    )
    qc.compose(
        controlled_oracle_less(n + 1, a, 1),
        [*regin, *anc_range1, *control],
        inplace=True,
    )
    qc.cx(control, anc_range1)

    return qc

def modfma(n: int, a: int, L: int) -> QuantumCircuit:
    x, y = QuantumRegister(n), QuantumRegister(n + 1)
    qc = QuantumCircuit(x, y)
    # Write your code here:

    ancs = QuantumRegister(3)
    qc.add_register(ancs)

    for idx in range(n):
        add = a * (2**idx) % L
        qc.compose(cmodadd(n, add, L), [*y, x[idx], *ancs], inplace=True)

    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library import RYGate
import numpy as np
import math

def qft(n):
    qc = QuantumCircuit(n)

    thetas = []
    for k in range(0, 1 + n):
        thetas.append(2 * math.pi / (2**k))

    for idx in range(0, n):
        qc.h(n - 1 - idx)
        for jdx in range(idx + 1, n):
            thetaidx = jdx - idx + 1
            qc.cp(thetas[thetaidx], n - 1 - jdx, n - 1 - idx)

    for idx in range(0, n // 2):
        qc.swap(idx, n - idx - 1)

    return qc

def add(n: int, a: int) -> QuantumCircuit:
    k = QuantumRegister(n)
    qc = QuantumCircuit(k)
    # Write your code here:

    qc.compose(qft(n), inplace=True)

    for idx in range(n):
        theta = 2 * a * math.pi * (2**idx) / (2**n)
        qc.p(theta, k[idx])

    qc.compose(qft(n).inverse(), inplace=True)

    return qc

def controlled_add(n: int, a: int, control_count: int) -> QuantumCircuit:
    k, c = QuantumRegister(n), QuantumRegister(control_count)
    qc = QuantumCircuit(k, c)
    # Write your code here:

    qc.compose(qft(n), inplace=True)

    for idx in range(n):
        theta = 2 * a * math.pi * (2**idx) / (2**n)
        qc.mcp(theta, c, k[idx])

    qc.compose(qft(n).inverse(), inplace=True)

    return qc

def oracle_less(bitcount: int, n: int) -> QuantumCircuit:
    regin, regout = QuantumRegister(bitcount), QuantumRegister(1)
    qc = QuantumCircuit(regin, regout)

    if n >= 2**bitcount:
        qc.x(regout)
        return qc

    bitrep = bin(n)[2:].zfill(bitcount)[::-1]
    masks = []

    for idx in range(bitcount):
        if bitrep[idx] == "1":
            mask = ("0" + bitrep[idx + 1 :]).rjust(bitcount, "*")
            masks.append(mask)

    flipped = [False] * bitcount
    for mask in masks:
        controls = []
        for idx in range(bitcount):
            if mask[idx] == "*":
                continue

            controls.append(regin[idx])
            if (mask[idx] == "0") != (flipped[idx]):
                flipped[idx] = not flipped[idx]
                qc.x(regin[idx])

        if len(controls) != 0:
            qc.mcx(controls, regout)

    for idx in range(bitcount):
        if flipped[idx]:
            qc.x(regin[idx])

    return qc

def controlled_oracle_less(bitcount: int, n: int, control_count: int) -> QuantumCircuit:
    regin, regout = QuantumRegister(bitcount), QuantumRegister(1)
    control = QuantumRegister(control_count)
    qc = QuantumCircuit(regin, regout, control)

    if n >= 2**bitcount:
        qc.mcx(control, regout)
        return qc

    bitrep = bin(n)[2:].zfill(bitcount)[::-1]
    masks = []

    for idx in range(bitcount):
        if bitrep[idx] == "1":
            mask = ("0" + bitrep[idx + 1 :]).rjust(bitcount, "*")
            masks.append(mask)

    flipped = [False] * bitcount
    for mask in masks:
        regin_controls = []
        for idx in range(bitcount):
            if mask[idx] == "*":
                continue

            regin_controls.append(regin[idx])
            if (mask[idx] == "0") != (flipped[idx]):
                flipped[idx] = not flipped[idx]
                qc.mcx(control, regin[idx])

        if len(regin_controls) != 0:
            qc.mcx([*regin_controls, *control], regout)

    for idx in range(bitcount):
        if flipped[idx]:
            qc.mcx(control, regin[idx])

    return qc

def modadd(n: int, a: int, L: int) -> QuantumCircuit:
    regin = QuantumRegister(n + 1)
    qc = QuantumCircuit(regin)
    # Write your code here:

    anc_range1 = QuantumRegister(1)
    anc_range2 = QuantumRegister(1)
    anc_range3 = QuantumRegister(1)
    qc.add_register(anc_range1)
    qc.add_register(anc_range2)
    qc.add_register(anc_range3)

    qc.x(anc_range1)
    qc.compose(oracle_less(n + 1, L), [*regin, *anc_range2], inplace=True)
    qc.compose(oracle_less(n + 1, L - a), [*regin, *anc_range1], inplace=True)
    qc.ccx(anc_range1, anc_range2, anc_range3)

    qc.compose(add(n + 1, a), inplace=True)
    qc.compose(controlled_add(n + 1, -L, 1), [*regin, *anc_range3], inplace=True)
    qc.ccx(anc_range1, anc_range2, anc_range3)

    qc.x(anc_range2)
    qc.x(regin[-1])
    qc.ccx(regin[-1], anc_range2, anc_range3)
    qc.x(regin[-1])
    qc.compose(controlled_add(n + 1, L, 1), [*regin, *anc_range3], inplace=True)

    qc.compose(
        oracle_less(n + 1, 2 ** (n + 1) + 1 - L), [*regin, *anc_range3], inplace=True
    )
    qc.compose(oracle_less(n + 1, L), [*regin, *anc_range3], inplace=True)

    qc.x(anc_range2)
    qc.compose(oracle_less(n + 1, L), [*regin, *anc_range2], inplace=True)

    qc.compose(oracle_less(n + 1, L), [*regin, *anc_range1], inplace=True)
    qc.compose(oracle_less(n + 1, a), [*regin, *anc_range1], inplace=True)
    qc.x(anc_range1)

    return qc

def cmodadd(n: int, a: int, L: int) -> QuantumCircuit:
    """in(n+1), control, anc1, anc2, anc3"""
    regin = QuantumRegister(n + 1)
    control = QuantumRegister(1)
    qc = QuantumCircuit(regin, control)
    # Write your code here:

    anc_range1 = QuantumRegister(1)
    anc_range2 = QuantumRegister(1)
    anc_range3 = QuantumRegister(1)
    qc.add_register(anc_range1)
    qc.add_register(anc_range2)
    qc.add_register(anc_range3)

    qc.cx(control, anc_range1)
    qc.compose(
        controlled_oracle_less(n + 1, L, 1),
        [*regin, *anc_range2, *control],
        inplace=True,
    )
    qc.compose(
        controlled_oracle_less(n + 1, L - a, 1),
        [*regin, *anc_range1, *control],
        inplace=True,
    )
    qc.mcx([*control, anc_range1, anc_range2], anc_range3)

    qc.compose(controlled_add(n + 1, a, 1), [*regin, *control], inplace=True)
    qc.compose(
        controlled_add(n + 1, -L, 2), [*regin, *anc_range3, *control], inplace=True
    )
    qc.mcx([anc_range1, anc_range2, *control], anc_range3)

    qc.cx(control, anc_range2)
    qc.cx(control, regin[-1])
    qc.mcx([regin[-1], *anc_range2, *control], anc_range3)
    qc.cx(control, regin[-1])
    qc.compose(
        controlled_add(n + 1, L, 2), [*regin, *anc_range3, *control], inplace=True
    )

    qc.compose(
        controlled_oracle_less(n + 1, 2 ** (n + 1) + 1 - L, 1),
        [*regin, *anc_range3, *control],
        inplace=True,
    )
    qc.compose(
        controlled_oracle_less(n + 1, L, 1),
        [*regin, *anc_range3, *control],
        inplace=True,
    )

    qc.cx(control, anc_range2)
    qc.compose(
        controlled_oracle_less(n + 1, L, 1),
        [*regin, *anc_range2, *control],
        inplace=True,
    )

    qc.compose(
        controlled_oracle_less(n + 1, L, 1),
        [*regin, *anc_range1, *control],
        inplace=True,
    )
    qc.compose(
        controlled_oracle_less(n + 1, a, 1),
        [*regin, *anc_range1, *control],
        inplace=True,
    )
    qc.cx(control, anc_range1)

    return qc

def solve(n: int, a: int, L: int) -> QuantumCircuit:
    x, y = QuantumRegister(n), QuantumRegister(n + 1)
    qc = QuantumCircuit(x, y)
    # Write your code here:

    ancs = QuantumRegister(3)
    qc.add_register(ancs)

    for idx in range(n):
        add = a * (2**idx) % L
        qc.compose(cmodadd(n, add, L), [*y, x[idx], *ancs], inplace=True)

    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister
import math

def solve(n: int, a: int, L: int) -> QuantumCircuit:
    x, y = QuantumRegister(n), QuantumRegister(n + 1)
    qc = QuantumCircuit(x, y)
    # Write your code here:
    for i in range(n):
        qc.compose(add_mod(n,(a*2**i)%L,L).control(1),qubits = [i]+list(range(n,2*n+1)), inplace=True)

    return qc

def add_mod(n: int, a: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n + 1)
    # Write your code here:
    qc.compose(add(n+1,2**n-L+a), inplace=True)
    qc.compose(pack(n,2**n-L+a,2**n+a), inplace=True)
    qc.compose(add(n+1,a), inplace=True)

    return qc

def pack(n: int, s: int, t: int) -> QuantumCircuit:
    qc = QuantumCircuit(n + 1)
    # Write your code here:
    qc.compose(add(n,-t).control(1),qubits = [n]+list(range(n)), inplace=True)
    qc.x(n)
    qc.compose(add(n,-s).control(1),qubits = [n]+list(range(n)), inplace=True)
    qc.x(n)
    return qc

def add(n,a):
    qc = QuantumCircuit(n)
    for i in range(n-1,-1,-1):
        qc.h(i)
        for j in range(i-1,-1,-1):
            qc.cp(2*math.pi/2**(i-j+1),j,i)
    for k in range(n//2):
        qc.swap(k,n-1-k)
    for i in range(n):
        qc.p(2*math.pi*a/2**(n-i),i)
    for i in range(n-1,-1,-1):
        qc.h(i)
        for j in range(i-1,-1,-1):
            qc.cp(-2*math.pi/2**(i-j+1),j,i)
    for k in range(n//2):
        qc.swap(k,n-1-k)
    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister
import math

def solve(n: int, a: int, L: int) -> QuantumCircuit:
    x, y = QuantumRegister(n), QuantumRegister(n + 1)
    qc = QuantumCircuit(x, y)
    # Write your code here:
    for i in range(n):
        qc.compose(add_mod(n,(a*2**i)%L,L).control(1),qubits = [i]+list(range(n,2*n+1)), inplace=True)

    return qc

def add_mod(n: int, a: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n + 1)
    # Write your code here:
    qc.compose(add(n+1,2**n-L+a), inplace=True)
    qc.compose(pack(n,2**n-L+a,2**n+a), inplace=True)
    qc.compose(add(n+1,a), inplace=True)

    return qc

def pack(n: int, s: int, t: int) -> QuantumCircuit:
    qc = QuantumCircuit(n + 1)
    # Write your code here:
    qc.compose(qft(n),qubits = list(range(n)), inplace=True)
    qc.compose(shift(n,-t).control(1),qubits = [n]+list(range(n)), inplace=True)
    qc.x(n)
    qc.compose(shift(n,-s).control(1),qubits = [n]+list(range(n)), inplace=True)
    qc.x(n)
    qc.compose(iqft(n),qubits = list(range(n)), inplace=True)
    return qc

def add(n,a):
    qc = QuantumCircuit(n)
    qc.compose(qft(n), inplace=True)
    qc.compose(shift(n,a), inplace=True)
    qc.compose(iqft(n), inplace=True)
    return qc

def qft(n):
    qc = QuantumCircuit(n)
    for i in range(n-1,-1,-1):
        qc.h(i)
        for j in range(i-1,-1,-1):
            qc.cp(2*math.pi/2**(i-j+1),j,i)
    for k in range(n//2):
        qc.swap(k,n-1-k)
    return qc

def iqft(n):
    qc = QuantumCircuit(n)
    for i in range(n-1,-1,-1):
        qc.h(i)
        for j in range(i-1,-1,-1):
            qc.cp(-2*math.pi/2**(i-j+1),j,i)
    for k in range(n//2):
        qc.swap(k,n-1-k)
    return qc

def shift(n,a):
    qc = QuantumCircuit(n)
    for i in range(n):
        qc.p(2*math.pi*a/2**(n-i),i)
    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library import QFT

def solve(n: int, a: int, L: int) -> QuantumCircuit:
    # Create quantum registers
    x, y = QuantumRegister(n), QuantumRegister(n + 1)
    qc = QuantumCircuit(x, y)

    # Step 1: Apply QFT to input register
    qft = QFT(n, do_swaps=False)
    qc.append(qft, x[:])

    # Step 2: Phase rotations based on modular multiplication
    for i in range(n):
        for j in range(i + 1):
            # Calculate phase for controlled rotation
            phase = (2 * (a * 2**(i-j)) % L) / L
            # Add controlled phase rotation
            qc.cp(2 * pi * phase, x[j], y[i])

    # Step 3: Apply inverse QFT
    qft_dagger = QFT(n, do_swaps=False).inverse()
    qc.append(qft_dagger, x[:])

    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister
from math import pi

def qft(qc: QuantumCircuit, q: QuantumRegister, n: int):
    """Implement QFT from scratch"""
    for i in range(n):
        qc.h(q[i])
        for j in range(i+1, n):
            qc.cp(pi/2**(j-i), q[j], q[i])

def inverse_qft(qc: QuantumCircuit, q: QuantumRegister, n: int):
    """Implement inverse QFT from scratch"""
    for i in range(n-1, -1, -1):
        for j in range(n-1, i, -1):
            qc.cp(-pi/2**(j-i), q[j], q[i])
        qc.h(q[i])

def solve(n: int, a: int, L: int) -> QuantumCircuit:
    # Create quantum registers
    x, y = QuantumRegister(n), QuantumRegister(n + 1)
    qc = QuantumCircuit(x, y)

    # Step 1: Apply custom QFT to input register
    qft(qc, x, n)

    # Step 2: Phase rotations based on modular multiplication
    for i in range(n):
        for j in range(i + 1):
            # Calculate phase for controlled rotation
            phase = (2 * (a * 2**(i-j)) % L) / L
            qc.cp(2 * pi * phase, x[j], y[i])

    # Step 3: Apply custom inverse QFT
    inverse_qft(qc, x, n)

    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister

def qft(n: int, inverse=False):
    """Manually implement the Quantum Fourier Transform (QFT)"""
    qc = QuantumCircuit(n)
    for j in range(n):
        qc.h(j)
        for k in range(j + 1, n):
            qc.cp(-np.pi / 2**(k - j), k, j)  # Controlled phase gate
    if inverse:
        qc = qc.inverse()  # Take inverse if needed
    return qc

def modular_addition(n: int, a: int):
    """Implement modular addition using QFT and controlled phase gates."""
    qc = QuantumCircuit(n)

    # Apply QFT
    qc.append(qft(n), range(n))

    # Apply phase shifts to encode addition
    for i in range(n):
        if (a >> i) & 1:  # Check if bit i of 'a' is set
            qc.p(np.pi / 2**(n - i - 1), i)

    # Apply inverse QFT
    qc.append(qft(n, inverse=True), range(n))

    return qc

def solve(n: int, a: int) -> QuantumCircuit:
    """Controlled constant addition circuit."""
    k_reg = QuantumRegister(n, name='k')
    c_reg = QuantumRegister(1, name='c')  # Control qubit
    qc = QuantumCircuit(k_reg, c_reg)

    # Controlled modular addition: Apply only if control qubit is 1
    controlled_add = modular_addition(n, a).control(1)

    qc.append(controlled_add, [c_reg[0]] + k_reg[:])

    return qc
'''


'''python
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister

def manual_qft(n):
    """Constructs the Quantum Fourier Transform (QFT) without using the Qiskit QFT library."""
    qc = QuantumCircuit(n)
    for j in range(n):
        qc.h(j)
        for k in range(j + 1, n):
            qc.cp(np.pi / 2**(k - j), k, j)
    return qc

def manual_iqft(n):
    """Constructs the Inverse Quantum Fourier Transform (IQFT) manually."""
    return manual_qft(n).inverse()

def controlled_modular_addition(n, a):
    """Implements controlled modular addition using QFT and controlled phase shifts."""
    qc = QuantumCircuit(n + 1)  # +1 for the control qubit

    # Apply QFT to the lower n qubits
    qft_circuit = manual_qft(n)
    qc.append(qft_circuit, range(n))

    # Apply controlled phase shifts based on 'a'
    for i in range(n):
        if (a >> i) & 1:  # Check if bit i of 'a' is set
            qc.cp(np.pi / 2**(n - i - 1), n, i)  # Controlled phase shift by control qubit

    # Apply inverse QFT
    iqft_circuit = manual_iqft(n)
    qc.append(iqft_circuit, range(n))

    return qc

def solve(n: int, a: int) -> QuantumCircuit:
    """Implements the Controlled Constant Addition circuit while following constraints."""
    k_reg = QuantumRegister(n, name='k')  # Register for 'k'
    c_reg = QuantumRegister(1, name='c')  # Control qubit
    qc = QuantumCircuit(k_reg, c_reg)

    # Controlled addition: Applied only if c = 1
    controlled_add = controlled_modular_addition(n, a).to_gate(label="C-ADD(a)").control(1)
    qc.append(controlled_add, [c_reg[0]] + k_reg[:])

    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister

def controlled_modular_addition(n, a):
    """Implements controlled modular addition using bitwise operations."""
    qc = QuantumCircuit(n + 1)  # Extra qubit for control

    for i in range(n):
        if (a >> i) & 1:  # If the i-th bit of 'a' is 1
            qc.cx(n, i)  # Controlled-X: If control is 1, flip bit i of 'k'

    return qc

def solve(n: int, a: int) -> QuantumCircuit:
    """Constructs an optimized controlled modular addition circuit."""
    k_reg = QuantumRegister(n, name='k')  # Register for k
    c_reg = QuantumRegister(1, name='c')  # Control qubit
    qc = QuantumCircuit(k_reg, c_reg)

    # Apply controlled modular addition (bitwise controlled-X operations)
    controlled_add = controlled_modular_addition(n, a).to_gate(label="C-ADD(a)").control(1)

    qc.append(controlled_add, [c_reg[0]] + k_reg[:])

    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library import RYGate
import numpy as np
import math

def qft(n):
    qc = QuantumCircuit(n)

    thetas = []
    for k in range(0, 1 + n):
        thetas.append(2 * math.pi / (2**k))

    for idx in range(0, n):
        qc.h(n - 1 - idx)
        for jdx in range(idx + 1, n):
            thetaidx = jdx - idx + 1
            qc.cp(thetas[thetaidx], n - 1 - jdx, n - 1 - idx)

    for idx in range(0, n // 2):
        qc.swap(idx, n - idx - 1)

    return qc

def add(n: int, a: int) -> QuantumCircuit:
    k = QuantumRegister(n)
    qc = QuantumCircuit(k)
    # Write your code here:

    qc.compose(qft(n), inplace=True)

    for idx in range(n):
        theta = 2 * a * math.pi * (2**idx) / (2**n)
        qc.p(theta, k[idx])

    qc.compose(qft(n).inverse(), inplace=True)

    return qc

def controlled_add(n: int, a: int, control_count: int) -> QuantumCircuit:
    k, c = QuantumRegister(n), QuantumRegister(control_count)
    qc = QuantumCircuit(k, c)
    # Write your code here:

    qc.compose(qft(n), inplace=True)

    for idx in range(n):
        theta = 2 * a * math.pi * (2**idx) / (2**n)
        qc.mcp(theta, c, k[idx])

    qc.compose(qft(n).inverse(), inplace=True)

    return qc

def oracle_less(bitcount: int, n: int) -> QuantumCircuit:
    regin, regout = QuantumRegister(bitcount), QuantumRegister(1)
    qc = QuantumCircuit(regin, regout)

    if n >= 2**bitcount:
        qc.x(regout)
        return qc

    bitrep = bin(n)[2:].zfill(bitcount)[::-1]
    masks = []

    for idx in range(bitcount):
        if bitrep[idx] == "1":
            mask = ("0" + bitrep[idx + 1 :]).rjust(bitcount, "*")
            masks.append(mask)

    flipped = [False] * bitcount
    for mask in masks:
        controls = []
        for idx in range(bitcount):
            if mask[idx] == "*":
                continue

            controls.append(regin[idx])
            if (mask[idx] == "0") != (flipped[idx]):
                flipped[idx] = not flipped[idx]
                qc.x(regin[idx])

        if len(controls) != 0:
            qc.mcx(controls, regout)

    for idx in range(bitcount):
        if flipped[idx]:
            qc.x(regin[idx])

    return qc

def controlled_oracle_less(bitcount: int, n: int, control_count: int) -> QuantumCircuit:
    regin, regout = QuantumRegister(bitcount), QuantumRegister(1)
    control = QuantumRegister(control_count)
    qc = QuantumCircuit(regin, regout, control)

    if n >= 2**bitcount:
        qc.mcx(control, regout)
        return qc

    bitrep = bin(n)[2:].zfill(bitcount)[::-1]
    masks = []

    for idx in range(bitcount):
        if bitrep[idx] == "1":
            mask = ("0" + bitrep[idx + 1 :]).rjust(bitcount, "*")
            masks.append(mask)

    flipped = [False] * bitcount
    for mask in masks:
        regin_controls = []
        for idx in range(bitcount):
            if mask[idx] == "*":
                continue

            regin_controls.append(regin[idx])
            if (mask[idx] == "0") != (flipped[idx]):
                flipped[idx] = not flipped[idx]
                qc.mcx(control, regin[idx])

        if len(regin_controls) != 0:
            qc.mcx([*regin_controls, *control], regout)

    for idx in range(bitcount):
        if flipped[idx]:
            qc.mcx(control, regin[idx])

    return qc

def modadd(n: int, a: int, L: int) -> QuantumCircuit:
    regin = QuantumRegister(n + 1)
    qc = QuantumCircuit(regin)
    # Write your code here:

    anc_range1 = QuantumRegister(1)
    anc_range2 = QuantumRegister(1)
    anc_range3 = QuantumRegister(1)
    qc.add_register(anc_range1)
    qc.add_register(anc_range2)
    qc.add_register(anc_range3)

    qc.x(anc_range1)
    qc.compose(oracle_less(n + 1, L), [*regin, *anc_range2], inplace=True)
    qc.compose(oracle_less(n + 1, L - a), [*regin, *anc_range1], inplace=True)
    qc.ccx(anc_range1, anc_range2, anc_range3)

    qc.compose(add(n + 1, a), inplace=True)
    qc.compose(controlled_add(n + 1, -L, 1), [*regin, *anc_range3], inplace=True)
    qc.ccx(anc_range1, anc_range2, anc_range3)

    qc.x(anc_range2)
    qc.x(regin[-1])
    qc.ccx(regin[-1], anc_range2, anc_range3)
    qc.x(regin[-1])
    qc.compose(controlled_add(n + 1, L, 1), [*regin, *anc_range3], inplace=True)

    qc.compose(
        oracle_less(n + 1, 2 ** (n + 1) + 1 - L), [*regin, *anc_range3], inplace=True
    )
    qc.compose(oracle_less(n + 1, L), [*regin, *anc_range3], inplace=True)

    qc.x(anc_range2)
    qc.compose(oracle_less(n + 1, L), [*regin, *anc_range2], inplace=True)

    qc.compose(oracle_less(n + 1, L), [*regin, *anc_range1], inplace=True)
    qc.compose(oracle_less(n + 1, a), [*regin, *anc_range1], inplace=True)
    qc.x(anc_range1)

    return qc

def cmodadd(n: int, a: int, L: int) -> QuantumCircuit:
    """in(n+1), control, anc1, anc2, anc3"""
    regin = QuantumRegister(n + 1)
    control = QuantumRegister(1)
    qc = QuantumCircuit(regin, control)
    # Write your code here:

    anc_range1 = QuantumRegister(1)
    anc_range2 = QuantumRegister(1)
    anc_range3 = QuantumRegister(1)
    qc.add_register(anc_range1)
    qc.add_register(anc_range2)
    qc.add_register(anc_range3)

    qc.cx(control, anc_range1)
    qc.compose(
        controlled_oracle_less(n + 1, L, 1),
        [*regin, *anc_range2, *control],
        inplace=True,
    )
    qc.compose(
        controlled_oracle_less(n + 1, L - a, 1),
        [*regin, *anc_range1, *control],
        inplace=True,
    )
    qc.mcx([*control, anc_range1, anc_range2], anc_range3)

    qc.compose(controlled_add(n + 1, a, 1), [*regin, *control], inplace=True)
    qc.compose(
        controlled_add(n + 1, -L, 2), [*regin, *anc_range3, *control], inplace=True
    )
    qc.mcx([anc_range1, anc_range2, *control], anc_range3)

    qc.cx(control, anc_range2)
    qc.cx(control, regin[-1])
    qc.mcx([regin[-1], *anc_range2, *control], anc_range3)
    qc.cx(control, regin[-1])
    qc.compose(
        controlled_add(n + 1, L, 2), [*regin, *anc_range3, *control], inplace=True
    )

    qc.compose(
        controlled_oracle_less(n + 1, 2 ** (n + 1) + 1 - L, 1),
        [*regin, *anc_range3, *control],
        inplace=True,
    )
    qc.compose(
        controlled_oracle_less(n + 1, L, 1),
        [*regin, *anc_range3, *control],
        inplace=True,
    )

    qc.cx(control, anc_range2)
    qc.compose(
        controlled_oracle_less(n + 1, L, 1),
        [*regin, *anc_range2, *control],
        inplace=True,
    )

    qc.compose(
        controlled_oracle_less(n + 1, L, 1),
        [*regin, *anc_range1, *control],
        inplace=True,
    )
    qc.compose(
        controlled_oracle_less(n + 1, a, 1),
        [*regin, *anc_range1, *control],
        inplace=True,
    )
    qc.cx(control, anc_range1)

    return qc

def cmodfma(n: int, a: int, L: int) -> QuantumCircuit:
    x, y = QuantumRegister(n), QuantumRegister(n + 1)
    qc = QuantumCircuit(x, y)
    # Write your code here:

    ancs = QuantumRegister(3)
    qc.add_register(ancs)

    for idx in range(n):
        add = a * (2**idx) % L
        qc.compose(cmodadd(n, add, L), [*y, x[idx], *ancs], inplace=True)

    return qc

def solve(n: int, a: int, L: int) -> QuantumCircuit:
    x, y = QuantumRegister(n), QuantumRegister(n + 1)
    qc = QuantumCircuit(x, y)
    # Write your code here:

    ancs = QuantumRegister(3)
    qc.add_register(ancs)

    qc.compose(cmodfma(n, a, L), inplace=True)

    for idx in range(n):
        qc.swap(x[idx], y[idx])

    qc.compose(cmodfma(n, -pow(a, -1, L), L), inplace=True)

    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister

def solve(n: int, a: int, L: int) -> QuantumCircuit:
    x = QuantumRegister(n)  # Register for input x
    y = QuantumRegister(n + 1)  # Register for output ax mod L
    qc = QuantumCircuit(x, y)

    # We will implement the multiplication by a and then take mod L
    # We will use a series of controlled additions to achieve this.

    # We need to add a * x to the output register
    for i in range(n):
        if (a >> i) & 1:  # Check if the i-th bit of a is set
            # We will add x to the output register controlled by the i-th qubit of x
            for j in range(n + 1):
                # Controlled addition of x to y
                qc.cx(x[i], y[j])  # Controlled-X gate to add x to y

    # Now we need to apply the modulo operation
    # We will use a series of Toffoli gates to implement the modulo operation
    # This is a simplified version and may not be the most efficient way to implement mod L
    # but it will work for small values of n and L.

    # We will use a classical approach to implement the modulo operation
    # by checking if the value exceeds L and then subtracting L if necessary.
    # This is a naive implementation and may need optimization for larger values.

    # For simplicity, we will assume L is a power of 2, which is true for the given constraints.
    # We will use the last qubit of y to store the carry for the modulo operation.

    # Example: if L = 2^n, we can simply ignore the overflow bits.
    # This is a placeholder for the actual modulo operation.
    # In practice, you would need to implement a more complex circuit to handle arbitrary L.

    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister
import math

def solve(n: int, a: int, L: int) -> QuantumCircuit:
    x, y = QuantumRegister(n), QuantumRegister(n + 1)
    qc = QuantumCircuit(x, y)
    # Write your code here:
    qc.compose(add_multi_mod(n,a,L),inplace=True)
    gcd,x,y = extended_euclidean(a,L)
    a_inv = x % L
    #print(a_inv)
    for i in range(n):
        qc.cx(i,n+i)
        qc.cx(n+i,i)
        qc.cx(i,n+i)
    qc.compose(add_multi_mod(n,L-a_inv,L),inplace=True)
    return qc

def extended_euclidean(a: int, b: int) -> tuple[int, int, int]:
    # when b == 0:
    if b == 0:
        return a, 1, 0

    # recursive step
    gcd, x1, y1 = extended_euclidean(b, a % b)

    # update x and y
    x = y1
    y = x1 - (a // b) * y1

    return gcd, x, y

def add_multi_mod(n: int, a: int, L: int) -> QuantumCircuit:
    x, y = QuantumRegister(n), QuantumRegister(n + 1)
    qc = QuantumCircuit(x, y)
    # Write your code here:
    for i in range(n):
        qc.compose(add_mod(n,(a*2**i)%L,L).control(1),qubits = [i]+list(range(n,2*n+1)), inplace=True)

    return qc

def add_mod(n: int, a: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n + 1)
    # Write your code here:
    qc.compose(add(n+1,2**n-L+a), inplace=True)
    qc.compose(pack(n,2**n-L+a,2**n+a), inplace=True)
    qc.compose(add(n+1,a), inplace=True)

    return qc

def pack(n: int, s: int, t: int) -> QuantumCircuit:
    qc = QuantumCircuit(n + 1)
    # Write your code here:
    qc.compose(qft(n),qubits = list(range(n)), inplace=True)
    qc.compose(shift(n,-t).control(1),qubits = [n]+list(range(n)), inplace=True)
    qc.x(n)
    qc.compose(shift(n,-s).control(1),qubits = [n]+list(range(n)), inplace=True)
    qc.x(n)
    qc.compose(iqft(n),qubits = list(range(n)), inplace=True)
    return qc

def add(n,a):
    qc = QuantumCircuit(n)
    qc.compose(qft(n), inplace=True)
    qc.compose(shift(n,a), inplace=True)
    qc.compose(iqft(n), inplace=True)
    return qc

def qft(n):
    qc = QuantumCircuit(n)
    for i in range(n-1,-1,-1):
        qc.h(i)
        for j in range(i-1,-1,-1):
            qc.cp(2*math.pi/2**(i-j+1),j,i)
    for k in range(n//2):
        qc.swap(k,n-1-k)
    return qc

def iqft(n):
    qc = QuantumCircuit(n)
    for i in range(n-1,-1,-1):
        qc.h(i)
        for j in range(i-1,-1,-1):
            qc.cp(-2*math.pi/2**(i-j+1),j,i)
    for k in range(n//2):
        qc.swap(k,n-1-k)
    return qc

def shift(n,a):
    qc = QuantumCircuit(n)
    for i in range(n):
        qc.p(2*math.pi*a/2**(n-i),i)
    return qc
'''


'''python
from qiskit import QuantumCircuit, QuantumRegister
import math

def solve(n: int, a: int, L: int) -> QuantumCircuit:
    x, y = QuantumRegister(n), QuantumRegister(n + 1)
    qc = QuantumCircuit(x, y)
    # Write your code here:
    qc.compose(add_multi_mod(n,a,L),inplace=True)
    gcd,x,y = extended_euclidean(a,L)
    a_inv = x % L
    #print(a_inv)
    for i in range(n):
        qc.cx(i,n+i)
        qc.cx(n+i,i)
        qc.cx(i,n+i)
    qc.compose(add_multi_mod(n,L-a_inv,L),inplace=True)
    return qc

def extended_euclidean(a: int, b: int) -> tuple[int, int, int]:
    # when b == 0:
    if b == 0:
        return a, 1, 0

    # recursive step
    gcd, x1, y1 = extended_euclidean(b, a % b)

    # update x and y
    x = y1
    y = x1 - (a // b) * y1

    return gcd, x, y

def add_multi_mod(n: int, a: int, L: int) -> QuantumCircuit:
    x, y = QuantumRegister(n), QuantumRegister(n + 1)
    qc = QuantumCircuit(x, y)
    # Write your code here:
    qc.compose(qft(n+1),qubits = list(range(n,2*n+1)), inplace=True)
    for i in range(n):
        qc.compose(add_mod(n,(a*2**i)%L,L).control(1),qubits = [i]+list(range(n,2*n+1)), inplace=True)
    qc.compose(iqft(n+1),qubits = list(range(n,2*n+1)), inplace=True)

    return qc

def add_mod(n: int, a: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n + 1)
    # Write your code here:
    qc.compose(shift(n+1,2**n-L+a), inplace=True)
    qc.compose(iqft(n+1), inplace=True)
    qc.compose(pack(n,2**n-L+a,2**n+a), inplace=True)
    qc.compose(qft(n+1), inplace=True)
    qc.compose(shift(n+1,a), inplace=True)

    return qc

def pack(n: int, s: int, t: int) -> QuantumCircuit:
    qc = QuantumCircuit(n + 1)
    # Write your code here:
    qc.compose(qft(n),qubits = list(range(n)), inplace=True)
    qc.compose(shift(n,-t).control(1),qubits = [n]+list(range(n)), inplace=True)
    qc.x(n)
    qc.compose(shift(n,-s).control(1),qubits = [n]+list(range(n)), inplace=True)
    qc.x(n)
    qc.compose(iqft(n),qubits = list(range(n)), inplace=True)
    return qc

def add(n,a):
    qc = QuantumCircuit(n)
    qc.compose(qft(n), inplace=True)
    qc.compose(shift(n,a), inplace=True)
    qc.compose(iqft(n), inplace=True)
    return qc

def qft(n):
    qc = QuantumCircuit(n)
    for i in range(n-1,-1,-1):
        qc.h(i)
        for j in range(i-1,-1,-1):
            qc.cp(2*math.pi/2**(i-j+1),j,i)
    for k in range(n//2):
        qc.swap(k,n-1-k)
    return qc

def iqft(n):
    qc = QuantumCircuit(n)
    for i in range(n-1,-1,-1):
        qc.h(i)
        for j in range(i-1,-1,-1):
            qc.cp(-2*math.pi/2**(i-j+1),j,i)
    for k in range(n//2):
        qc.swap(k,n-1-k)
    return qc

def shift(n,a):
    qc = QuantumCircuit(n)
    for i in range(n):
        qc.p(2*math.pi*a/2**(n-i),i)
    return qc
'''