'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import PhaseGate
import math

def Rt(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    for i in range(n):
        if not (L >> i) & 1:
            continue
        for j in range(i + 1, n):
            if not (L >> j) & 1:
                qc.x(j)
        qc.x(i)
        if i == n - 1:
            qc.p(math.pi / 3, i)
        else:
            qc.append(PhaseGate(math.pi / 3).control(n - i - 1), range(i, n))
        qc.x(i)
        for j in range(i + 1, n):
            if not (L >> j) & 1:
                qc.x(j)

    return qc

def Rs(n: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    qc.x(range(n))

    if n == 1:
        qc.p(math.pi / 3, 0)
    else:
        qc.append(PhaseGate(math.pi / 3).control(n - 1), range(n))

    qc.x(range(n))

    return qc

def U(m: int, n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    if m == 0:
        qc.h(range(n))
        return qc

    u = U(m - 1, n, L)

    qc.compose(u, inplace=True)
    qc.compose(Rt(n, L), inplace=True)
    qc.compose(u.inverse(), inplace=True)
    qc.compose(Rs(n), inplace=True)
    qc.compose(u, inplace=True)

    return qc

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    k = math.floor(math.log2(L))
    if k == 0:
        return qc

    m = 3
    qc.compose(U(m, k, L), inplace=True)

    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import MCMT
import math

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:
    v = []
    s = 0
    for j in range(n - 1, -1, -1):
        if ((L-1) >> j) & 1:
            s += (1 << j)
            theta = 2 * math.acos(((1 << j) / ((1 << j) + (L - s))) ** 0.5)
            if(len(v) == 0):
                qc.ry(theta, j)
            else:
                for k in range(len(v)):
                    if v[k] == 0:
                        qc.x((n - 1) - k)
                cnh = MCMT('h', (n - 1) - j,1)
                qc.compose(cnh,qubits = list(range(n - 1, j - 1, -1)),inplace=True)
                qc.mcp(theta, qc.qregs[0][(j+1):], qc.qregs[0][j])
                cnh = MCMT('h', (n - 1) - j,1)
                qc.compose(cnh,qubits = list(range(n - 1, j - 1, -1)),inplace=True)

                for k in range(len(v)):
                    if v[k] == 0:
                        qc.x((n - 1) - k)
            v.append(1)
        else:
            v.append(0)
            continue
    for j in range(n - 1):
        if v[j] == 1:
            for k in range(j):
                if(v[k] == 0):
                    qc.x((n - 1) - k)
            qc.x((n - 1) - j)
            cnh = MCMT('h',j + 1,1)
            for k in range((n - 1) - j):
                qc.compose(cnh,qubits = list(range(n - 1, (n - 1) - (j + 1), -1)) + [k],inplace=True)
            for k in range(j):
                if(v[k] == 0):
                    qc.x((n - 1) - k)
            qc.x((n - 1) - j)
    return qc
'''


'''python
from qiskit import QuantumCircuit
import math

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:
    l = math.ceil(math.log2(L))
    for i in range(l):
        qc.h(i)
    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import PhaseGate
import math

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:
    def Rt(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    for i in range(n):
        if not (L >> i) & 1:
            continue
        for j in range(i + 1, n):
            if not (L >> j) & 1:
                qc.x(j)
        qc.x(i)
        if i == n - 1:
            qc.p(math.pi / 3, i)
        else:
            qc.append(PhaseGate(math.pi / 3).control(n - i - 1), range(i, n))
        qc.x(i)
        for j in range(i + 1, n):
            if not (L >> j) & 1:
                qc.x(j)

    return qc

def Rs(n: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    qc.x(range(n))

    if n == 1:
        qc.p(math.pi / 3, 0)
    else:
        qc.append(PhaseGate(math.pi / 3).control(n - 1), range(n))

    qc.x(range(n))

    return qc

def U(m: int, n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    if m == 0:
        qc.h(range(n))
        return qc

    u = U(m - 1, n, L)

    qc.compose(u, inplace=True)
    qc.compose(Rt(n, L), inplace=True)
    qc.compose(u.inverse(), inplace=True)
    qc.compose(Rs(n), inplace=True)
    qc.compose(u, inplace=True)

    return qc

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    k = math.ceil(math.log2(L))
    if k == 0:
        return qc

    m = 3
    qc.compose(U(m, k, L), inplace=True)

    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import PhaseGate
import math

def Rt(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    for i in range(n):
        if not (L >> i) & 1:
            continue
        for j in range(i + 1, n):
            if not (L >> j) & 1:
                qc.x(j)
        qc.x(i)
        if i == n - 1:
            qc.p(math.pi / 3, i)
        else:
            qc.append(PhaseGate(math.pi / 3).control(n - i - 1), range(i, n))
        qc.x(i)
        for j in range(i + 1, n):
            if not (L >> j) & 1:
                qc.x(j)

    return qc

def Rs(n: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    qc.x(range(n))

    if n == 1:
        qc.p(math.pi / 3, 0)
    else:
        qc.append(PhaseGate(math.pi / 3).control(n - 1), range(n))

    qc.x(range(n))

    return qc

def U(m: int, n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    if m == 0:
        qc.h(range(n))
        return qc

    u = U(m - 1, n, L)

    qc.compose(u, inplace=True)
    qc.compose(Rt(n, L), inplace=True)
    qc.compose(u.inverse(), inplace=True)
    qc.compose(Rs(n), inplace=True)
    qc.compose(u, inplace=True)

    return qc

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:

    k = math.ceil(math.log2(L))
    if k == 0:
        return qc

    m = 3
    qc.compose(U(m, k, L), inplace=True)

    return qc
'''


'''python
import math

from qiskit import QuantumCircuit
from qiskit.circuit.library import HGate
from qiskit.circuit.library import RYGate

def nya(l):
    global qc
    if len(l) == 1:
      qc.h(l[0])
    else:
      print(l)
      qc.append(HGate().control(len(l) - 1), l)

def nyan(p,l):
    global qc
    if len(l) == 1:
      qc.ry(p,l[0])
    else:
      qc.append(RYGate(p).control(len(l) - 1), l)

def solve2(n,L,now,l,msk,msk2):
  if now == -1:
    return
  global qc
  f = []
  g = []
  for i in range(2 ** n):
    if i & msk2 == msk:
      if (i & (1 << now)) > 0:
        g.append(i)
      else:
        f.append(i)
  if max(f) >= L:
    solve2(n,L,now-1,l,msk,msk2 | (1 << now))
  else:
    g = g[0:L - max(f) - 1]
    p = len(g)/(len(f)+len(g))
    nyan(math.atan((p/(1-p)) ** 0.5)*2, l + [now])
    l.append(now)
    msk |= (1 << now)
    solve2(n,L,now-1,l,msk,msk2 | (1 << now))

    qc.x(now)
    for i in range(0,now):
      nya(l + [i])
    qc.x(now)
    l.pop()

def solve(n: int, L: int) -> QuantumCircuit:
    global qc
    qc = QuantumCircuit(n)
    # Write your code here:
    solve2(n,L,n-1,[],0,0)
    return qc
'''


'''python
from qiskit import QuantumCircuit
import math
from qiskit.circuit.library import ZGate,XGate,RYGate

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    # Write your code here:

    # 左n bitが1になっている物の位相を反転
    def reverse(qubits,qc,start):
        if qubits-start>1:
            qc.append(ZGate().control(qubits - 1 - start), range(start,qubits))
        else:
            qc.z(start)

    # ある値をall_1に変更する操作
    # 左何bit目から操作するか指定
    def to_calcable(qubits,qc,n,start):
        for i in range(start,qubits):
            if not (n&(1<<i)):
                qc.x(i)

    d={}
    for i in range(1<<n):
        tmp=""
        for j in bin(i)[2:].rjust(n,"0"):
            tmp+=j
            d.setdefault(tmp,0)

    for i in range(L):
        s=bin(i)[2:].rjust(n,"0")
        tmp=""
        for i in s:
            tmp+=i
            d[tmp]+=1

    # 指定したbit(ゼロ状態)が0になる確率をratioにする

    # 指定したcontroll bitがすべて1の場合にbit(ゼロ状態)が0になる確率をratioにする
    def crotate(qc,bits,p0):
        theta=math.acos(p0*2-1)
        if len(bits)==1:
            qc.ry(theta,bits[0])
        else:
            qc.append(RYGate(theta).control(len(bits)-1),bits)

    def dfs(prefix,bit,qc,n):
        # print("call",prefix,bit)
        prefix0=prefix+"0"
        prefix1=prefix+"1"
        v=int(prefix.ljust(n,"0"),2)

        if bit==-1 or d.get(prefix0)+d.get(prefix1)==0:return
        if prefix=="":
            p0=d[prefix0]/(d[prefix0]+d[prefix1])
            to_calcable(n,qc,v,0)
            crotate(qc,[bit],p0)
            to_calcable(n,qc,v,0)
            dfs(prefix0,bit-1,qc,n)
            dfs(prefix1,bit-1,qc,n)
        elif bit>=0:
            # print(prefix,d[prefix+"0"],d[prefix+"1"])
            p0=d[prefix0]/(d[prefix0]+d[prefix1])
            if p0==0.5:
                to_calcable(n,qc,v,0)
                for b in range(bit,-1,-1):
                    crotate(qc,list(range(n-1,bit,-1))+[b],p0)
                to_calcable(n,qc,v,0)
            else:
                to_calcable(n,qc,v,0)
                crotate(qc,list(range(n-1,bit-1,-1)),p0)
                to_calcable(n,qc,v,0)
                dfs(prefix0,bit-1,qc,n)
                dfs(prefix1,bit-1,qc,n)

    dfs("",n-1,qc,n)
    # depth = qc.depth()
    # print("量子回路の深さ:", depth)
    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import HGate, RYGate
import math

def add_rule(qc: QuantumCircuit, n: int, suffix: list[int], Lpre: int) -> None:
    k = len(suffix)
    split_idx = n - k - 1

    #print(f"Lpre={Lpre}, split_idx={split_idx}")
    num = 1 << split_idx
    denom = Lpre
    #print(f"{num}/{denom}")
    theta = math.acos(math.sqrt(num/denom)) * 2
    if k > 0:
        idx = n - 1
        for bit in suffix:
            if bit == 0:
                qc.x(idx)
            idx -= 1
        #print("ry", k, range(split_idx + 1, n))
        qc.append(RYGate(theta).control(k), list(range(split_idx + 1, n)) + [split_idx])
        idx = n - 1
        for bit in suffix:
            if bit == 0:
                qc.x(idx)
            idx -= 1
    else:
        qc.ry(theta, n - 1)

    #print(suffix)
    for i in range(0, split_idx):
        idx = n - 1
        for bit in suffix + [0]:
            if bit == 0:
                qc.x(idx)
            idx -= 1

        size = k + 1
        qubits = list(range(split_idx, n)) + [i]
        #print(size, qubits)
        qc.append(HGate().control(size), qubits)

        idx = n - 1
        for bit in suffix + [0]:
            if bit == 0:
                qc.x(idx)
            idx -= 1

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    if L == (1 << n):
        for i in range(n):
            qc.h(i)
        return qc

    cnt = 0
    suffix = []
    Lpre = L
    for i in range(n - 1, -1, -1):
        if L & (1 << i):
            add_rule(qc, n, suffix, Lpre)
            if cnt == 1:
                break
            Lpre -= (1 << i)
            suffix.append(1)
        else:
            suffix.append(0)

        cnt += 1

    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import HGate, RYGate
import math

def add_rule(qc: QuantumCircuit, n: int, suffix: list[int], Lpre: int) -> None:
    k = len(suffix)
    split_idx = n - k - 1

    #print(f"Lpre={Lpre}, split_idx={split_idx}")
    num = 1 << split_idx
    denom = Lpre
    #print(f"{num}/{denom}")
    theta = math.acos(math.sqrt(num/denom)) * 2
    if k > 0:
        idx = n - 1
        for bit in suffix:
            if bit == 0:
                qc.x(idx)
            idx -= 1
        #print("ry", k, range(split_idx + 1, n))
        qc.append(RYGate(theta).control(k), list(range(split_idx + 1, n)) + [split_idx])
        idx = n - 1
        for bit in suffix:
            if bit == 0:
                qc.x(idx)
            idx -= 1
    else:
        qc.ry(theta, n - 1)

    #print(suffix)
    for i in range(0, split_idx):
        idx = n - 1
        for bit in suffix + [0]:
            if bit == 0:
                qc.x(idx)
            idx -= 1

        size = k + 1
        qubits = list(range(split_idx, n)) + [i]
        #print(size, qubits)
        qc.append(HGate().control(size), qubits)

        idx = n - 1
        for bit in suffix + [0]:
            if bit == 0:
                qc.x(idx)
            idx -= 1

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    if L == (1 << n):
        for i in range(n):
            qc.h(i)
        return qc

    cnt = 0
    suffix = []
    Lpre = L
    for i in range(n - 1, -1, -1):
        if L & (1 << i):
            add_rule(qc, n, suffix, Lpre)
            Lpre -= (1 << i)
            suffix.append(1)
        else:
            suffix.append(0)

        cnt += 1

    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import PhaseGate
import math

def Rt(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    for i in range(n):
        if not (L >> i) & 1:
            continue
        for j in range(i + 1, n):
            if not (L >> j) & 1:
                qc.x(j)
        qc.x(i)
        if i == n - 1:
            qc.p(math.pi / 3, i)
        else:
            qc.append(PhaseGate(math.pi / 3).control(n - i - 1), range(i, n))
        qc.x(i)
        for j in range(i + 1, n):
            if not (L >> j) & 1:
                qc.x(j)

    return qc

def Rs(n: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    qc.x(range(n))

    if n == 1:
        qc.p(math.pi / 3, 0)
    else:
        qc.append(PhaseGate(math.pi / 3).control(n - 1), range(n))

    qc.x(range(n))

    return qc

def U(m: int, n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    if m == 0:
        qc.h(range(n))
        return qc

    u = U(m - 1, n, L)

    qc.compose(u, inplace=True)
    qc.compose(Rt(n, L), inplace=True)
    qc.compose(u.inverse(), inplace=True)
    qc.compose(Rs(n), inplace=True)
    qc.compose(u, inplace=True)

    return qc

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    k = math.ceil(math.log2(L))
    if k == 0:
        return qc

    m = 3
    qc.compose(U(m, k, L), inplace=True)

    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import HGate
from math import atan2, sqrt

def seq(low, hi):
  return list(range(low, hi))

def solve(n : int, L : int) -> QuantumCircuit:
  qc = QuantumCircuit(n)
  n = int.bit_length(L)

  def bit(i : int) -> bool:
    return (L & (1 << i)) != 0

  assert bit(n-1)
  assert 2 ** (n-1) < L <= 2 ** n
  # Split |0> to a|0> + b|0>
  #   where |a|^2 : |b|^2 = 2^{n-1} : L - 2^{n-1}
  # \cos(t/2) = \sqrt(2^{n-1}/L)
  # \sin(t/2) = \sqrt((L - 2^{n-1})/L)
  # e.g for L = 11 = 0b1011, 8 for 0xxx, 3 for 1xxx
  t = 2 * atan2(sqrt(L-2**(n-1)), sqrt(2**(n-1)))
  qc.ry(t, n-1)

  # Distribute lower bits for |0> to all 2^{n-1} patterns.
  qc.x(n-1)
  for i in range(n-1):
    qc.ch(n-1, i)
  qc.x(n-1)

  for i in range(n-2, -1, -1):
    if not bit(i):
      qc.x(i)
      continue

    # e.g. for L = 0b1011 and i = 1, 2 for 100x, 1 for 101x
    s = L & ((1 << (i+1)) - 1)
    t = 2 * atan2(sqrt(s-2**(i-1)), sqrt(2**(i-1)))
    qc.mcry(t, seq(i+1, n), i)

    if i > 0:
      qc.mcx(seq(i+1, n), i)
      for j in range(i):
        qc.append(HGate().control(n-i), seq(i, n) + [j])
      qc.mcx(seq(i+1, n), i)

  for i in range(n):
    if not bit(i):
      qc.x(i)

  return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import RYGate, HGate
import math

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:
    if L == 2**n:
        for j in range(n):
            qc.h(j)
    else:
        flip = []
        for i in range(n):
            if L >= 2**(n-1-i):
                theta = math.acos(math.sqrt(2**(n-1-i)/L)) * 2
                if i != 0:
                    qc.mcry(theta, [n-1-_ for _ in range(i)], n-1-i)
                else:
                    qc.ry(theta, n-1)
                qc.x(n-1-i)
                for j in range(n - 1 - i):
                    qc.append(HGate().control(i + 1), [n-1-_ for _ in range(i + 1)] + [j])
                qc.x(n-1-i)
            else:
                qc.x(n-1-i)
                flip.append(n-1-i)
            L %= 2**(n-1-i)
        for f in flip:
            qc.x(f)
    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import RYGate, HGate
import math

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:
    if L == 2**n:
        for j in range(n):
            qc.h(j)
    else:
        flip = []
        for i in range(n):
            if L >= 2**(n-1-i):
                theta = math.acos(math.sqrt(2**(n-1-i)/L)) * 2
                if i != 0:
                    qc.append(RYGate(theta).control(i), [n-1-_ for _ in range(i + 1)])
                else:
                    qc.ry(theta, n-1)
                qc.x(n-1-i)
                for j in range(n - 1 - i):
                    qc.append(HGate().control(i + 1), [n-1-_ for _ in range(i + 1)] + [j])
                qc.x(n-1-i)
            else:
                qc.x(n-1-i)
                flip.append(n-1-i)
            L %= 2**(n-1-i)
        for f in flip:
            qc.x(f)
    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import HGate, RYGate
import math

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:
    for i in range(n):
        cnt_0 = (L >> (i+1)) + 1
        cnt_1 = L >> (i+1)
        theta = math.acos(math.sqrt(cnt_0 / (cnt_0 + cnt_1))) * 2
        if L >> i & 1 ==  1:
            same = ''
            for j in range(i-1, -1, -1):
                nxt = L >> j & 1
                if nxt == 1:
                    qc.append(HGate().control(i-j, ctrl_state=same+'0'), range(j, i+1))
                same += str(nxt)
            same = ''
            for j in range(i-1, -1, -1):
                nxt = L >> j & 1
                if nxt == 0:
                    qc.append(RYGate(theta).control(i-j, ctrl_state=same+'1'), range(j, i+1))
                same += str(nxt)
            if i == 0:
                qc.ry(theta, 0)
            else:
                qc.append(RYGate(theta).control(i, ctrl_state=same), range(i+1))
        else:
            same = ''
            for j in range(i-1, -1, -1):
                nxt = L >> j & 1
                if nxt == 1:
                    qc.append(RYGate(theta).control(i-j, ctrl_state=same+'0'), range(j, i+1))
                same += str(nxt)
            same = ''
            for j in range(i-1, -1, -1):
                nxt = L >> j & 1
                if nxt == 0:
                    qc.append(HGate().control(i-j, ctrl_state=same+'1'), range(j, i+1))
                same += str(nxt)
            if i == 0:
                qc.h(0)
            else:
                qc.append(HGate().control(i, ctrl_state=same), range(i+1))

    return qc
'''


'''python
from qiskit import QuantumCircuit

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:
    # Compute l0, l1, ..., lk
    l_values = [int(i) for i in np.binary_repr(M)[::-1]]

    # Apply X gates on qubits at positions l1, l2, ..., lk
    for l in l_values[1:]:
        qc.x(l)

    # Set M0 = 2^l0
    M0 = 2**l_values[0]

    # If l0 > 0, apply Hadamard gates on the rightmost l0 qubits
    if l_values[0] > 0:
        qc.h(range(l_values[0]))

        # Apply rotation gate RY(theta0) on qubit ql1
        theta0 = -2 * np.arccos(np.sqrt(M0/M))
        qc.ry(theta0, l_values[1])

        # Apply controlled Hadamard gate on qubits lm, lm + 1, ..., lm+1 − 1 conditioned on qlm+1 being 0
        for i in range(l_values[0], l_values[1]):
            qc.ch(i, l_values[1])

    # Apply controlled RY gates and controlled Hadamard gates for m = 1 to k - 1
    for m in range(1, len(l_values) - 1):
        theta_m = -2 * np.arccos(np.sqrt(2*l_values[m]/(M - 2**(m-1))))
        qc.cry(theta_m, l_values[m], l_values[m+1])

        for i in range(l_values[m], l_values[m+1]):
            qc.ch(i, l_values[m+1])
    return qc
'''


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

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:
    # Compute l0, l1, ..., lk
    l_values = [int(i) for i in np.binary_repr(M)[::-1]]

    # Apply X gates on qubits at positions l1, l2, ..., lk
    for l in l_values[1:]:
        qc.x(l)

    # Set M0 = 2^l0
    M0 = 2**l_values[0]

    # If l0 > 0, apply Hadamard gates on the rightmost l0 qubits
    if l_values[0] > 0:
        qc.h(range(l_values[0]))

        # Apply rotation gate RY(theta0) on qubit ql1
        theta0 = -2 * np.arccos(np.sqrt(M0/M))
        qc.ry(theta0, l_values[1])

        # Apply controlled Hadamard gate on qubits lm, lm + 1, ..., lm+1 − 1 conditioned on qlm+1 being 0
        for i in range(l_values[0], l_values[1]):
            qc.ch(i, l_values[1])

    # Apply controlled RY gates and controlled Hadamard gates for m = 1 to k - 1
    for m in range(1, len(l_values) - 1):
        theta_m = -2 * np.arccos(np.sqrt(2*l_values[m]/(M - 2**(m-1))))
        qc.cry(theta_m, l_values[m], l_values[m+1])

        for i in range(l_values[m], l_values[m+1]):
            qc.ch(i, l_values[m+1])
    return qc
'''


'''python
from qiskit import QuantumCircuit
import math

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:
    # Compute l0, l1, ..., lk
    binary_rep = bin(M)[2:][::-1]
    l_values = [int(bit) for bit in binary_rep]

    # Apply X gates on qubits at positions l1, l2, ..., lk
    for l in l_values[1:]:
        qc.x(l)

    # Set M0 = 2^l0
    M0 = 2**l_values[0]

    # If l0 > 0, apply Hadamard gates on the rightmost l0 qubits
    if l_values[0] > 0:
        qc.h(range(l_values[0]))

        # Apply rotation gate RY(theta0) on qubit ql1
        theta0 = -2 * qc.circuit.acos(qc.circuit.sqrt(M0/M))
        qc.ry(theta0, l_values[1])

        # Apply controlled Hadamard gate on qubits lm, lm + 1, ..., lm+1 − 1 conditioned on qlm+1 being 0
        for i in range(l_values[0], l_values[1]):
            qc.ch(i, l_values[1])

    # Apply controlled RY gates and controlled Hadamard gates for m = 1 to k - 1
    for m in range(1, len(l_values) - 1):
        theta_m = -2 * qc.circuit.acos(qc.circuit.sqrt(2*l_values[m]/(M - 2**(m-1))))
        qc.cry(theta_m, l_values[m], l_values[m+1])

        for i in range(l_values[m], l_values[m+1]):
            qc.ch(i, l_values[m+1])
    return qc
'''


'''python
from qiskit import QuantumCircuit

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:
    # Compute l0, l1, ..., lk
    binary_rep = bin(L)[2:][::-1]
    l_values = [int(bit) for bit in binary_rep]

    # Apply X gates on qubits at positions l1, l2, ..., lk
    for l in l_values[1:]:
        qc.x(l)

    # Set M0 = 2^l0
    M0 = 2**l_values[0]

    # If l0 > 0, apply Hadamard gates on the rightmost l0 qubits
    if l_values[0] > 0:
        qc.h(range(l_values[0]))

        # Apply rotation gate RY(theta0) on qubit ql1
        theta0 = -2 * qc.circuit.acos(qc.circuit.sqrt(M0/L))
        qc.ry(theta0, l_values[1])

        # Apply controlled Hadamard gate on qubits lm, lm + 1, ..., lm+1 − 1 conditioned on qlm+1 being 0
        for i in range(l_values[0], l_values[1]):
            qc.ch(i, l_values[1])

    # Apply controlled RY gates and controlled Hadamard gates for m = 1 to k - 1
    for m in range(1, len(l_values) - 1):
        theta_m = -2 * qc.circuit.acos(qc.circuit.sqrt(2*l_values[m]/(L - 2**(m-1))))
        qc.cry(theta_m, l_values[m], l_values[m+1])

        for i in range(l_values[m], l_values[m+1]):
            qc.ch(i, l_values[m+1])
    return qc
'''


'''python
from qiskit import QuantumCircuit

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:
    for i in range(n):
        qc.h(i)

    # Compute l0, l1, ..., lk
    binary_rep = bin(L)[2:][::-1]
    l_values = [int(bit) for bit in binary_rep]

    # Apply X gates on qubits at positions l1, l2, ..., lk
    for l in l_values[1:]:
        qc.x(l)

    # Set M0 = 2^l0
    M0 = 2**l_values[0]

    # If l0 > 0, apply Hadamard gates on the rightmost l0 qubits
    if l_values[0] > 0:
        qc.h(range(l_values[0]))

        # Apply rotation gate RY(theta0) on qubit ql1
        theta0 = -2 * qc.circuit.acos(qc.circuit.sqrt(M0/L))
        qc.ry(theta0, l_values[1])

        # Apply controlled Hadamard gate on qubits lm, lm + 1, ..., lm+1 − 1 conditioned on qlm+1 being 0
        for i in range(l_values[0], l_values[1]):
            qc.ch(i, l_values[1])

    # Apply controlled RY gates and controlled Hadamard gates for m = 1 to k - 1
    for m in range(1, len(l_values) - 1):
        theta_m = -2 * qc.circuit.acos(qc.circuit.sqrt(2*l_values[m]/(L - 2**(m-1))))
        qc.cry(theta_m, l_values[m], l_values[m+1])

        for i in range(l_values[m], l_values[m+1]):
            qc.ch(i, l_values[m+1])
    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import RYGate
import math

def apply_controlled_ry_all_except_k(qc: QuantumCircuit, th: float, k:int):
    n = qc.num_qubits
    control_qubits = [i for i in range(n) if i != k]
    target_qubit = k
    controlled_ry = RYGate(th).control(len(control_qubits))
    qc.append(controlled_ry, control_qubits + [target_qubit])

def make_qc(qc: QuantumCircuit, L: int, k: int, state: int) -> QuantumCircuit:
    if(L == 1):
        return qc

    n = qc.num_qubits

    for i in range(n):
        if not ((1 >> i) & state):
            qc.x(i)

    L1 = int((L + 1) / 2)
    L2 = L - L1

    th = 2 * math.atan(math.sqrt(L2 / L1))
    apply_controlled_ry_all_except_k(qc, th, k)

    for i in range(n):
        if not ((1 >> i) & state):
            qc.x(i)

    make_qc(qc, L1, k + 1, state)
    make_qc(qc, L2, k + 1, state + 2 ** k)

    return qc

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:

    make_qc(qc, L, 0, 0)
    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import RYGate
import math

def apply_controlled_ry_all_except_k(qc: QuantumCircuit, th: float, k:int):
    n = qc.num_qubits
    control_qubits = [i for i in range(n) if i != k]
    target_qubit = k
    controlled_ry = RYGate(th).control(len(control_qubits))
    qc.append(controlled_ry, control_qubits + [target_qubit])

def make_qc(qc: QuantumCircuit, L: int, k: int, state: int) -> QuantumCircuit:
    if(L == 1):
        return qc

    n = qc.num_qubits

    for i in range(n):
        if not ((1 << i) & state):
            qc.x(i)

    L1 = int((L + 1) / 2)
    L2 = L - L1

    th = 2 * math.atan(math.sqrt(L2 / L1))
    apply_controlled_ry_all_except_k(qc, th, k)

    for i in range(n):
        if not ((1 << i) & state):
            qc.x(i)

    make_qc(qc, L1, k + 1, state)
    make_qc(qc, L2, k + 1, state + 2 ** k)

    return qc

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:

    make_qc(qc, L, 0, 0)
    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import RYGate
import math

def apply_controlled_ry_all_except_k(qc: QuantumCircuit, th: float, k:int):
    n = qc.num_qubits
    control_qubits = [i for i in range(n) if i != k]
    target_qubit = k
    controlled_ry = RYGate(th).control(len(control_qubits))
    qc.append(controlled_ry, control_qubits + [target_qubit])

def make_qc(qc: QuantumCircuit, L: int, k: int, state: int) -> QuantumCircuit:
    if L == 1:
        return qc

    n = qc.num_qubits

    for i in range(n):
        if not ((1 << i) & state):
            qc.x(i)

    L1 = int((L + 1) / 2)
    L2 = L - L1

    th = 2 * math.atan(math.sqrt(L2 / L1))
    apply_controlled_ry_all_except_k(qc, th, k)

    for i in range(n):
        if not ((1 << i) & state):
            qc.x(i)

    make_qc(qc, L1, k + 1, state)
    make_qc(qc, L2, k + 1, state + 2 ** k)

    return qc

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:

    if n != 0:
        make_qc(qc, L, 0, 0)
    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import RYGate
import math

def apply_controlled_ry_all_except_k(qc: QuantumCircuit, th: float, k:int):
    n = qc.num_qubits
    control_qubits = [i for i in range(n) if i != k]
    target_qubit = k
    controlled_ry = RYGate(th).control(len(control_qubits))
    qc.append(controlled_ry, control_qubits + [target_qubit])

def make_qc(qc: QuantumCircuit, L: int, k: int, state: int) -> QuantumCircuit:
    if L == 1:
        return qc

    n = qc.num_qubits

    for i in range(n):
        if not ((1 << i) & state):
            qc.x(i)

    L1 = int((L + 1) / 2)
    L2 = L - L1

    th = 2 * math.atan(math.sqrt(L2 / L1))
    apply_controlled_ry_all_except_k(qc, th, k)

    for i in range(n):
        if not ((1 << i) & state):
            qc.x(i)

    make_qc(qc, L1, k + 1, state)
    make_qc(qc, L2, k + 1, state + 2 ** k)

    return qc

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:

    if n > 1:
        make_qc(qc, L, 0, 0)
    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import RYGate
import math

def apply_controlled_ry_all_except_k(qc: QuantumCircuit, th: float, k:int):
    n = qc.num_qubits
    control_qubits = [i for i in range(n) if i != k]
    target_qubit = k
    controlled_ry = RYGate(th).control(len(control_qubits))
    qc.append(controlled_ry, control_qubits + [target_qubit])

def make_qc(qc: QuantumCircuit, L: int, k: int, state: int) -> QuantumCircuit:
    if L == 1:
        return qc

    n = qc.num_qubits

    for i in range(n):
        if not ((1 << i) & state):
            qc.x(i)

    L1 = int((L + 1) / 2)
    L2 = L - L1

    th = 2 * math.atan(math.sqrt(L2 / L1))
    apply_controlled_ry_all_except_k(qc, th, k)

    for i in range(n):
        if not ((1 << i) & state):
            qc.x(i)

    make_qc(qc, L1, k + 1, state)
    make_qc(qc, L2, k + 1, state + 2 ** k)

    return qc

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:

    if n == 1:
        if L == 2:
            qc.h(0)

    else:
        make_qc(qc, L, 0, 0)
    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import RYGate, HGate
from math import sqrt, acos, asin

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    def rec(n: int, L: int, control: list[int]):
        if n == 0:
            return
        n -= 1
        w = 1 << n
        def RY():
            if control:
                qc.ry(theta, n)
            else:
                qc.append(RYGate(theta).control(len(control)), control + [n])
        if L <= w:
            qc.x(n)
            rec(n, L, control + [n])
            qc.x(n)
            return
        theta = asin(sqrt(w / L)) * 2
        def H(i):
            qc.append(HGate().control(len(control) + 1), control + [n, i])
        for i in range(n):
            H(i)
        qc.x(n)
        rec(n, L - w, control + [n])

    rec(n, L, [])

    return qc
'''


'''python
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit
from qiskit.circuit.library import RYGate, HGate
from math import sqrt, acos, asin

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    def rec(n: int, L: int, control: list[int]):
        if n == 0:
            return
        n -= 1
        w = 1 << n
        def RY():
            if control:
                qc.append(RYGate(theta).control(len(control)), control + [n])
            else:
                qc.ry(theta, n)
        if L <= w:
            qc.x(n)
            rec(n, L, control + [n])
            qc.x(n)
            return
        theta = asin(sqrt(w / L)) * 2
        RY()
        def H(i):
            qc.append(HGate().control(len(control) + 1), control + [n, i])
        for i in range(n):
            H(i)
        qc.x(n)
        rec(n, L - w, control + [n])

    rec(n, L, [])

    return qc

qc = solve(1, 2)
fig = qc.draw(output='mpl')
plt.show()
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import RYGate, HGate
from math import sqrt, acos, asin

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    def rec(n: int, L: int, control: list[int]):
        if n == 0:
            return
        n -= 1
        w = 1 << n
        def RY():
            if control:
                qc.append(RYGate(theta).control(len(control)), control + [n])
            else:
                qc.ry(theta, n)
        if L <= w:
            qc.x(n)
            rec(n, L, control + [n])
            qc.x(n)
            return
        theta = asin(sqrt(w / L)) * 2
        RY()
        def H(i):
            qc.append(HGate().control(len(control) + 1), control + [n, i])
        for i in range(n):
            H(i)
        qc.x(n)
        rec(n, L - w, control + [n])

    rec(n, L, [])

    return qc
'''


'''python
from qiskit import QuantumCircuit

def uniform_algorithm(M, n):
    # バイナリ表記の逆順で1の位置を取得
    binary_str = bin(M)[2:][::-1]
    print(binary_str)
    locations_of_1 = [i for i, bit in enumerate(binary_str) if bit == '1']
    print(locations_of_1)
    # 量子回路の初期化
    qc = QuantumCircuit(n)
    if n == 1:
        if M == 2:
            qc.h(0)
    elif not log2(M).is_integer():
        # Xゲートを指定の位置に適用
        for loc in locations_of_1[1:]:
            qc.append(XGate(), [loc])

        # M0が偶数の場合、右端のl0ビットに対してHadamardゲートを適用
        M0 = 2 ** locations_of_1[0]
        if M0 % 2 == 0:
            for i in range(locations_of_1[0]):
                qc.append(HGate(), [i])

        # 回転ゲートのパラメータ
        theta0 = -2 * acos(sqrt(M0 / M))

        # RYゲートを適用
        qc.append(RYGate(theta0), [locations_of_1[1]])

        # 制御Hadamardゲートを適用
        for i in range(locations_of_1[0], locations_of_1[1]):
            qc.x(locations_of_1[1])
            qc.append(HGate().control(), [locations_of_1[1], i])
            qc.x(locations_of_1[1])

        # k回の繰り返し
        Mm = M0
        for m in range(1, len(locations_of_1)-1):
            # 回転ゲートのパラメータ
            theta_m = -2 * acos(sqrt(2**locations_of_1[m] / (M - Mm)))

            # 制御RYゲートを適用
            qc.x(locations_of_1[m])
            qc.append(RYGate(theta_m).control(), [locations_of_1[m], locations_of_1[m+1]])
            qc.x(locations_of_1[m])
            # 制御Hadamardゲートを適用
            for i in range(locations_of_1[m], locations_of_1[m+1]):
                qc.x(locations_of_1[m+1])
                qc.append(HGate().control(), [locations_of_1[m+1],locations_of_1[m]])
                qc.x(locations_of_1[m+1])
            Mm += 2**locations_of_1[m]
    else:
        qc.h(range(int(log2(M))))

    return qc

def solve(n: int, L: int) -> QuantumCircuit:
    qc = uniform_algorithm(L,n)
    # Write your code here:

    return qc
'''


'''python
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.circuit.library import XGate, HGate, U3Gate, RYGate
from math import acos, sqrt, log2

def uniform_algorithm(M, n):
    # バイナリ表記の逆順で1の位置を取得
    binary_str = bin(M)[2:][::-1]
    print(binary_str)
    locations_of_1 = [i for i, bit in enumerate(binary_str) if bit == '1']
    print(locations_of_1)
    # 量子回路の初期化
    qc = QuantumCircuit(n)
    if n == 1:
        if M == 2:
            qc.h(0)
    elif not log2(M).is_integer():
        # Xゲートを指定の位置に適用
        for loc in locations_of_1[1:]:
            qc.append(XGate(), [loc])

        # M0が偶数の場合、右端のl0ビットに対してHadamardゲートを適用
        M0 = 2 ** locations_of_1[0]
        if M0 % 2 == 0:
            for i in range(locations_of_1[0]):
                qc.append(HGate(), [i])

        # 回転ゲートのパラメータ
        theta0 = -2 * acos(sqrt(M0 / M))

        # RYゲートを適用
        qc.append(RYGate(theta0), [locations_of_1[1]])

        # 制御Hadamardゲートを適用
        for i in range(locations_of_1[0], locations_of_1[1]):
            qc.x(locations_of_1[1])
            qc.append(HGate().control(), [locations_of_1[1], i])
            qc.x(locations_of_1[1])

        # k回の繰り返し
        Mm = M0
        for m in range(1, len(locations_of_1)-1):
            # 回転ゲートのパラメータ
            theta_m = -2 * acos(sqrt(2**locations_of_1[m] / (M - Mm)))

            # 制御RYゲートを適用
            qc.x(locations_of_1[m])
            qc.append(RYGate(theta_m).control(), [locations_of_1[m], locations_of_1[m+1]])
            qc.x(locations_of_1[m])
            # 制御Hadamardゲートを適用
            for i in range(locations_of_1[m], locations_of_1[m+1]):
                qc.x(locations_of_1[m+1])
                qc.append(HGate().control(), [locations_of_1[m+1],locations_of_1[m]])
                qc.x(locations_of_1[m+1])
            Mm += 2**locations_of_1[m]
    else:
        qc.h(range(int(log2(M))))

    return qc

def solve(n: int, L: int) -> QuantumCircuit:
    qc = uniform_algorithm(L,n)
    # Write your code here:

    return qc
'''


'''python
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.circuit.library import XGate, HGate, U3Gate, RYGate
from math import acos, sqrt, log2

def uniform_algorithm(M, n):
    # バイナリ表記の逆順で1の位置を取得
    binary_str = bin(M)[2:][::-1]
    print(binary_str)
    locations_of_1 = [i for i, bit in enumerate(binary_str) if bit == '1']
    print(locations_of_1)
    # 量子回路の初期化
    qc = QuantumCircuit(n)
    if n == 1:
        if M == 2:
            qc.h(0)
    elif not log2(M).is_integer():
        # Xゲートを指定の位置に適用
        for loc in locations_of_1[1:]:
            qc.append(XGate(), [loc])

        # M0が偶数の場合、右端のl0ビットに対してHadamardゲートを適用
        M0 = 2 ** locations_of_1[0]
        if M0 % 2 == 0:
            for i in range(locations_of_1[0]):
                qc.append(HGate(), [i])

        # 回転ゲートのパラメータ
        theta0 = -2 * acos(sqrt(M0 / M))

        # RYゲートを適用
        qc.append(RYGate(theta0), [locations_of_1[1]])

        # 制御Hadamardゲートを適用
        for i in range(locations_of_1[0], locations_of_1[1]):
            qc.x(locations_of_1[1])
            qc.append(HGate().control(), [locations_of_1[1], i])
            qc.x(locations_of_1[1])

        # k回の繰り返し
        Mm = M0
        for m in range(1, len(locations_of_1)-1):
            # 回転ゲートのパラメータ
            theta_m = -2 * acos(sqrt(2**locations_of_1[m] / (M - Mm)))

            # 制御RYゲートを適用
            qc.x(locations_of_1[m])
            qc.append(RYGate(theta_m).control(), [locations_of_1[m], locations_of_1[m+1]])
            qc.x(locations_of_1[m])
            # 制御Hadamardゲートを適用
            for i in range(locations_of_1[m], locations_of_1[m+1]):
                qc.x(locations_of_1[m+1])
                qc.append(HGate().control(), [locations_of_1[m+1],locations_of_1[m]])
                qc.x(locations_of_1[m+1])
            Mm += 2**locations_of_1[m]
    else:
        qc.h(range(int(log2(M))))

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

    return qc

def solve(n: int, L: int) -> QuantumCircuit:
    qc = uniform_algorithm(L,n)
    # Write your code here:

    return qc
'''


'''python
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.circuit.library import XGate, HGate, U3Gate, RYGate
from math import acos, sqrt, log2
def uniform_algorithm(M, n):
    # バイナリ表記の逆順で1の位置を取得
    binary_str = bin(M)[2:][::-1]
    print(binary_str)
    locations_of_1 = [i for i, bit in enumerate(binary_str) if bit == '1']
    print(locations_of_1)
    # 量子回路の初期化
    qc = QuantumCircuit(n)
    if n == 1:
        if M == 2:
            qc.h(0)
    elif not log2(M).is_integer():
        # Xゲートを指定の位置に適用
        for loc in locations_of_1[1:]:
            qc.append(XGate(), [loc])

        # M0が偶数の場合、右端のl0ビットに対してHadamardゲートを適用
        M0 = 2 ** locations_of_1[0]
        if M0 % 2 == 0:
            for i in range(locations_of_1[0]):
                qc.append(HGate(), [i])

        # 回転ゲートのパラメータ
        theta0 = -2 * acos(sqrt(M0 / M))

        # RYゲートを適用
        qc.append(RYGate(theta0), [locations_of_1[1]])

        # 制御Hadamardゲートを適用
        for i in range(locations_of_1[0], locations_of_1[1]):
            qc.x(locations_of_1[1])
            qc.append(HGate().control(), [locations_of_1[1], i])
            qc.x(locations_of_1[1])

        # k回の繰り返し
        Mm = M0
        print(len(locations_of_1))
        for m in range(1, len(locations_of_1)-1):
            print(m)
            # 回転ゲートのパラメータ
            theta_m = -2 * acos(sqrt(2**locations_of_1[m] / (M - Mm)))

            # 制御RYゲートを適用
            qc.x(locations_of_1[m])
            qc.append(RYGate(theta_m).control(), [locations_of_1[m], locations_of_1[m+1]])
            qc.x(locations_of_1[m])
            # 制御Hadamardゲートを適用
            for i in range(locations_of_1[m], locations_of_1[m+1]):
                qc.x(locations_of_1[m+1])
                qc.append(HGate().control(), [locations_of_1[m+1],i])
                qc.x(locations_of_1[m+1])
            Mm += 2**locations_of_1[m]
    else:
        qc.h(range(int(log2(M))))

    return qc

def solve(n: int, L: int) -> QuantumCircuit:
    qc = uniform_algorithm(L,n)
    # Write your code here:

    return qc
'''


'''python
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.circuit.library import XGate, HGate, U3Gate, RYGate
from math import acos, sqrt, log2
def uniform_algorithm(M, n):
    # バイナリ表記の逆順で1の位置を取得
    binary_str = bin(M)[2:][::-1]
    print(binary_str)
    locations_of_1 = [i for i, bit in enumerate(binary_str) if bit == '1']
    print(locations_of_1)
    # 量子回路の初期化
    qc = QuantumCircuit(n)
    f n == 1:
        if M == 2:
            qc.h(0)
    elif M == 1:
        qc.x(0)
        qc.x(0)
    elif not log2(M).is_integer():
        # Xゲートを指定の位置に適用
        for loc in locations_of_1[1:]:
            qc.append(XGate(), [loc])

        # M0が偶数の場合、右端のl0ビットに対してHadamardゲートを適用
        M0 = 2 ** locations_of_1[0]
        if M0 % 2 == 0:
            for i in range(locations_of_1[0]):
                qc.append(HGate(), [i])

        # 回転ゲートのパラメータ
        theta0 = -2 * acos(sqrt(M0 / M))

        # RYゲートを適用
        qc.append(RYGate(theta0), [locations_of_1[1]])

        # 制御Hadamardゲートを適用
        for i in range(locations_of_1[0], locations_of_1[1]):
            qc.x(locations_of_1[1])
            qc.append(HGate().control(), [locations_of_1[1], i])
            qc.x(locations_of_1[1])

        # k回の繰り返し
        Mm = M0
        print(len(locations_of_1))
        for m in range(1, len(locations_of_1)-1):
            print(m)
            # 回転ゲートのパラメータ
            theta_m = -2 * acos(sqrt(2**locations_of_1[m] / (M - Mm)))

            # 制御RYゲートを適用
            qc.x(locations_of_1[m])
            qc.append(RYGate(theta_m).control(), [locations_of_1[m], locations_of_1[m+1]])
            qc.x(locations_of_1[m])
            # 制御Hadamardゲートを適用
            for i in range(locations_of_1[m], locations_of_1[m+1]):
                qc.x(locations_of_1[m+1])
                qc.append(HGate().control(), [locations_of_1[m+1],i])
                qc.x(locations_of_1[m+1])
            Mm += 2**locations_of_1[m]
    else:
        qc.h(range(int(log2(M))))

    return qc

def solve(n: int, L: int) -> QuantumCircuit:
    qc = uniform_algorithm(L,n)
    # Write your code here:

    return qc
'''


'''python
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.circuit.library import XGate, HGate, U3Gate, RYGate
from math import acos, sqrt, log2
def uniform_algorithm(M, n):
    # バイナリ表記の逆順で1の位置を取得
    binary_str = bin(M)[2:][::-1]
    print(binary_str)
    locations_of_1 = [i for i, bit in enumerate(binary_str) if bit == '1']
    print(locations_of_1)
    # 量子回路の初期化
    qc = QuantumCircuit(n)
    if n == 1:
        if M == 2:
            qc.h(0)
    elif M == 1:
        qc.x(0)
        qc.x(0)
    elif not log2(M).is_integer():
        # Xゲートを指定の位置に適用
        for loc in locations_of_1[1:]:
            qc.append(XGate(), [loc])

        # M0が偶数の場合、右端のl0ビットに対してHadamardゲートを適用
        M0 = 2 ** locations_of_1[0]
        if M0 % 2 == 0:
            for i in range(locations_of_1[0]):
                qc.append(HGate(), [i])

        # 回転ゲートのパラメータ
        theta0 = -2 * acos(sqrt(M0 / M))

        # RYゲートを適用
        qc.append(RYGate(theta0), [locations_of_1[1]])

        # 制御Hadamardゲートを適用
        for i in range(locations_of_1[0], locations_of_1[1]):
            qc.x(locations_of_1[1])
            qc.append(HGate().control(), [locations_of_1[1], i])
            qc.x(locations_of_1[1])

        # k回の繰り返し
        Mm = M0
        print(len(locations_of_1))
        for m in range(1, len(locations_of_1)-1):
            print(m)
            # 回転ゲートのパラメータ
            theta_m = -2 * acos(sqrt(2**locations_of_1[m] / (M - Mm)))

            # 制御RYゲートを適用
            qc.x(locations_of_1[m])
            qc.append(RYGate(theta_m).control(), [locations_of_1[m], locations_of_1[m+1]])
            qc.x(locations_of_1[m])
            # 制御Hadamardゲートを適用
            for i in range(locations_of_1[m], locations_of_1[m+1]):
                qc.x(locations_of_1[m+1])
                qc.append(HGate().control(), [locations_of_1[m+1],i])
                qc.x(locations_of_1[m+1])
            Mm += 2**locations_of_1[m]
    else:
        qc.h(range(int(log2(M))))

    return qc

def solve(n: int, L: int) -> QuantumCircuit:
    qc = uniform_algorithm(L,n)
    # Write your code here:

    return qc
'''


'''python
from qiskit import QuantumCircuit
import math

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:
    coeff = 1/math.sqrt(L)
    qc.initialize([coeff]*L + [0]*(2**n-L))
    return qc.decompose(reps=5)
'''


'''python
from qiskit import QuantumCircuit
import math

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:
    coeff = 1/math.sqrt(L)
    qc.initialize([coeff]*L + [0]*(2**n-L))
    return qc.decompose(reps=10)
'''


'''python
from qiskit import QuantumCircuit
import math

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:
    coeff = 1/math.sqrt(L)
    qc.initialize([coeff]*L + [0]*(2**n-L))
    return qc.decompose(reps=15)
'''


'''python
from qiskit import QuantumCircuit
import math

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:
    coeff = 1/math.sqrt(L)
    qc.initialize([coeff]*L + [0]*(2**n-L))
    return qc.decompose(reps=20)
'''


'''python
from qiskit import QuantumCircuit

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    l=L-1
    k=0
    while l>0:
        maxi=0
        for i in range(n-1-k,-1,-1):
            if 1<<i > l:
                continue
            if 1<<i <=l and 1<<(i+1)>l:
                maxi=max(maxi,i)
                print(1<<(i))
                # if i>0:
                l2=L-1
                for k1 in range(n-1,i,-1):
                    if not (1<<k1)&l2:
                        qc.x(k1)
                clist=list(range(n-1,i,-1))+[i]
                cu3_gate = U3Gate(-math.acos(math.sqrt((1<<i))/math.sqrt(l+1))*2,math.pi,0).control(len(clist)-1)
                print(clist)
                qc.append(cu3_gate,clist)

                l2=L-1
                for k1 in range(n-1,i,-1):
                    if not (1<<k1)&l2:
                        qc.x(k1)

                qc.x(i)
                for j in range(n-1,maxi,-1):
                    qc.x(j)
                for j in range(0,i):
                    clist=list(range(n-1,i-1,-1))+[j]

                    c3h_gate = HGate().control(len(clist)-1)
                    print(clist)
                    qc.append(c3h_gate,clist)
                qc.x(i)
                for j in range(n-1,maxi,-1):
                    qc.x(j)

                k+=1
                l=l-(1<<i) # 最上位ビット削除

    return qc
'''


'''python
from qiskit import QuantumCircuit

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    l=L-1
    k=0
    while l>0:
        maxi=0
        for i in range(n-1-k,-1,-1):
            if 1<<i > l:
                continue
            if 1<<i <=l and 1<<(i+1)>l:
                maxi=max(maxi,i)
                print(1<<(i))
                # if i>0:
                l2=L-1
                for k1 in range(n-1,i,-1):
                    if not (1<<k1)&l2:
                        qc.x(k1)
                clist=list(range(n-1,i,-1))+[i]
                if len(clist)>1:
                    cu3_gate = U3Gate(-math.acos(math.sqrt((1<<i))/math.sqrt(l+1))*2,math.pi,0).control(len(clist)-1)
                    print(clist)
                    qc.append(cu3_gate,clist)
                else:
                    qc.u(-math.acos(math.sqrt((1<<i))/math.sqrt(l+1))*2,math.pi,0,i)

                l2=L-1
                for k1 in range(n-1,i,-1):
                    if not (1<<k1)&l2:
                        qc.x(k1)

                qc.x(i)
                for j in range(n-1,maxi,-1):
                    qc.x(j)
                for j in range(0,i):
                    clist=list(range(n-1,i-1,-1))+[j]

                    c3h_gate = HGate().control(len(clist)-1)
                    print(clist)
                    qc.append(c3h_gate,clist)
                qc.x(i)
                for j in range(n-1,maxi,-1):
                    qc.x(j)

                k+=1
                l=l-(1<<i) # 最上位ビット削除

    return qc
'''


'''python
from qiskit import QuantumCircuit

def c1(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:

    if L == 1:
        return qc

    while True:
        print(n)
        if L > 2 ** (n - 1):
            qc.h(range(n))
            return qc
        n -= 1

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    for i in range(500):
        c = c1(n, L)
        qc.append(c, range(n))

    return qc
'''


'''python
from qiskit import QuantumCircuit

def c1(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:

    if L == 1:
        return qc

    while True:
        print(n)
        if L > 2 ** (n - 1):
            qc.h(range(n))
            return qc
        n -= 1

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    c = c1(n, L)

    for _ in range(500):
        qc.append(c, range(n))

    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit import Aer, transpile, execute

def c1(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:

    if L == 1:
        return qc

    while True:
        print(n)
        if L > 2 ** (n - 1):
            qc.h(range(n))
            return qc
        n -= 1

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    c = c1(n, L)

    for _ in range(500):
        qc &= c

    return qc
'''


'''python
from qiskit import QuantumCircuit

def c1(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:

    if L == 1:
        return qc

    while True:
        print(n)
        if L > 2 ** (n - 1):
            qc.h(range(n))
            return qc
        n -= 1

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    c = c1(n, L)

    for _ in range(500):
        qc &= c

    return qc

solve(10, 100)
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import ZGate, PhaseGate
import math

def Rt(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    for i in range(n):
        if not (L >> i) & 1:
            continue
        for j in range(i + 1, n):
            if not (L >> j) & 1:
                qc.x(j)
        qc.x(i)
        if i == n - 1:
            qc.p(math.pi / 3, i)
        else:
            qc.append(PhaseGate(math.pi / 3).control(n - i - 1), range(i, n))
        qc.x(i)
        for j in range(i + 1, n):
            if not (L >> j) & 1:
                qc.x(j)

    return qc

def Rs(n: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    qc.x(range(n))

    if n == 1:
        qc.p(math.pi / 3, 0)
    else:
        qc.append(PhaseGate(math.pi / 3).control(n - 1), range(n))

    qc.x(range(n))

    return qc

def U(m: int, n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    if m == 0:
        qc.h(range(n))
        return qc

    u = U(m - 1, n, L)

    qc.compose(u, inplace=True)
    qc.compose(Rt(n, L), inplace=True)
    qc.compose(u.inverse(), inplace=True)
    qc.compose(Rs(n), inplace=True)
    qc.compose(u, inplace=True)

    return qc

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    if L == 1:
        return qc

    k = math.ceil(math.log2(L))
    qc.compose(U(3, k, L), inplace=True)

    return qc
'''


'''python
import math
from qiskit import QuantumCircuit
from qiskit.circuit.library import ZGate

def less_than_oracle(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    for i in range(n):
        if (L & (1 << i)) == 0:
            qc.x(i)
    for i in range(n):
        if (L & (1 << i)) != 0:
            qc.x(i)
            if i + 1 < n:
                qc.append(ZGate().control(n - i - 1), range(i, n))
            else:
                qc.z(i)
            qc.x(i)
    for i in range(n):
        if (L & (1 << i)) == 0:
            qc.x(i)
    return qc

def diffusion_oracle(n: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    for i in range(n):
        qc.h(i)
        qc.x(i)
    qc.append(ZGate().control(n - 1), range(n))
    for i in range(n):
        qc.x(i)
        qc.h(i)
    return qc

def make_three_uniform() -> QuantumCircuit:
    qc = QuantumCircuit(2)
    qc.h(0)
    qc.ry(math.asin(1 / 3), 0)
    qc.ch(0, 1)
    qc.x(0)
    return qc

def solve(n: int, L: int) -> QuantumCircuit:
    assert L < 2 ** n
    qc = QuantumCircuit(n)
    for i in range(n):
        qc.h(i)
    if L == (2 ** n) // 2:
        qc.h(n-1)
        return qc
    if L == (2 ** n) // 4 * 3:
        qc.h(n-1)
        qc.h(n-2)
        qc.append(make_three_uniform().to_gate(), [n - 2, n - 1])
        return qc

    theta = math.asin((L / (2 ** n)) ** 0.5)
    # print(f"{theta = }")
    less = less_than_oracle(n, L)
    diff = diffusion_oracle(n)
    for i in range(400):
        if math.sin((2 * i + 1) * theta) ** 2 > 0.9999:
            # print(f'break! {i = }')
            break
        qc.append(less.to_gate(), range(n))
        qc.append(diff.to_gate(), range(n))
    return qc

# if __name__ == "__main__":
#     from qiskit.quantum_info import Statevector
#     import numpy as np
#     import random

#     n = random.randint(2, 10)
#     L = random.randint(1, 2 ** n - 1)
#     # n = 2
#     # L = 2**(n-2)*3
#     # theta = L/N, and only broken when n/(4 theta) is a half integer
#     print(f"{n = } {L = }")
#     qc = solve(n, L)
#     sv = Statevector(qc)
#     # print(sv)
#     prob = (np.abs(sv) ** 2)
#     print(sum(prob[i] for i in range(L)))
#     print(f"{qc.depth() = }")
# #     sv = Statevector.from_label('+++')
# #     print(sv.evolve(qc))
'''


'''python
import math
from qiskit import QuantumCircuit
from qiskit.circuit.library import ZGate

def less_than_oracle(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    for i in range(n):
        if (L & (1 << i)) == 0:
            qc.x(i)
    for i in range(n):
        if (L & (1 << i)) != 0:
            qc.x(i)
            if i + 1 < n:
                qc.append(ZGate().control(n - i - 1), range(i, n))
            else:
                qc.z(i)
            qc.x(i)
    for i in range(n):
        if (L & (1 << i)) == 0:
            qc.x(i)
    return qc

def diffusion_oracle(n: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    for i in range(n):
        qc.h(i)
        qc.x(i)
    qc.append(ZGate().control(n - 1), range(n))
    for i in range(n):
        qc.x(i)
        qc.h(i)
    return qc

def make_three_uniform() -> QuantumCircuit:
    qc = QuantumCircuit(2)
    qc.h(0)
    qc.ry(math.asin(1 / 3), 0)
    qc.ch(0, 1)
    qc.x(0)
    return qc

def solve(n: int, L: int) -> QuantumCircuit:
    assert L <= 2 ** n
    qc = QuantumCircuit(n)
    for i in range(n):
        qc.h(i)
    if L == (2 ** n):
        return qc
    if L == (2 ** n) // 2:
        qc.h(n-1)
        return qc
    if L == (2 ** n) // 4 * 3:
        qc.h(n-1)
        qc.h(n-2)
        qc.append(make_three_uniform().to_gate(), [n - 2, n - 1])
        return qc

    theta = math.asin((L / (2 ** n)) ** 0.5)
    # print(f"{theta = }")
    less = less_than_oracle(n, L)
    diff = diffusion_oracle(n)
    for i in range(400):
        if math.sin((2 * i + 1) * theta) ** 2 > 0.9999:
            # print(f'break! {i = }')
            break
        qc.append(less.to_gate(), range(n))
        qc.append(diff.to_gate(), range(n))
    return qc

# if __name__ == "__main__":
#     from qiskit.quantum_info import Statevector
#     import numpy as np
#     import random

#     n = random.randint(2, 10)
#     L = random.randint(1, 2 ** n - 1)
#     # n = 2
#     # L = 2**(n-2)*3
#     # theta = L/N, and only broken when n/(4 theta) is a half integer
#     print(f"{n = } {L = }")
#     qc = solve(n, L)
#     sv = Statevector(qc)
#     # print(sv)
#     prob = (np.abs(sv) ** 2)
#     print(sum(prob[i] for i in range(L)))
#     print(f"{qc.depth() = }")
# #     sv = Statevector.from_label('+++')
# #     print(sv.evolve(qc))
'''


'''python
from qiskit import QuantumCircuit

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:
    for i in range(n):
        qc.h(i)

    for k in range(1, n):
        if L <= 2**(n-k):
            qc.x(n-k)
            qc.h(n-k)
    return qc
'''


'''python
from qiskit import QuantumCircuit

def solve(n: int, L: int) -> QuantumCircuit:
    if L == (1<<n):
        qc = QuantumCircuit(n)
        return qc
    else:
        numbin = bin(L + (1<<n))[3:]
        qc = QuantumCircuit(n)
        numbin = numbin.rstrip("0")
        print(numbin)
        if numbin[0]== "1":
            qc.x(n-1)
            qc.z(n-1)
            qc.x(n-1)
        else:
            qc.x(n-1)
        for pos, v in enumerate(numbin[1:]):
            pos += 1
            if v=="0":
                qc.x(n-1-pos)
            else:
                qc.x(n-1-pos)
                nn = pos + 1
                circuit=QuantumCircuit(nn)
                circuit.h(nn-1)
                gate = MCXGate(nn-1)
                circuit.append(gate, range(nn))
                circuit.h(nn-1)
                qc.append(circuit.to_gate(), range(n-1,n-2-pos,-1))
                qc.x(n-pos-1)
        for pos, v in enumerate(numbin):
            if v == "0":
                qc.x(n-pos-1)
        qc = qc.decompose()
        return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import ZGate, MCXGate, GroverOperator
import math

def get_oracle(n,L):
    if L == (1<<n):
        qc = QuantumCircuit(n)
        return qc
    numbin = bin(L + (1<<n))[3:]
    qc = QuantumCircuit(n)
    numbin = numbin.rstrip("0")
    print(numbin)
    if numbin[0]== "1":
        qc.x(n-1)
        qc.z(n-1)
        qc.x(n-1)
    else:
        qc.x(n-1)
    for pos, v in enumerate(numbin[1:]):
        pos += 1
        if v=="0":
            qc.x(n-1-pos)
        else:
            qc.x(n-1-pos)
            nn = pos + 1
            circuit=QuantumCircuit(nn)
            circuit.h(nn-1)
            gate = MCXGate(nn-1)
            circuit.append(gate, range(nn))
            circuit.h(nn-1)
            qc.append(circuit.to_gate(), range(n-1,n-2-pos,-1))
            qc.x(n-pos-1)
    for pos, v in enumerate(numbin):
        if v == "0":
            qc.x(n-pos-1)
    qc = qc.decompose()
    return qc

def mirror(oracle: QuantumCircuit, n_qubits: int, barrier: bool = False) -> QuantumCircuit:
    qc = QuantumCircuit(n_qubits)
    qc.append(oracle.inverse(), list(range(n_qubits)))
    qc.x(list(range(n_qubits)))
    qc.h(n_qubits-1)
    qc.mcx(list(range(n_qubits-1)), n_qubits-1)
    qc.h(n_qubits-1)
    qc.x(list(range(n_qubits)))
    qc.append(oracle, list(range(n_qubits)))
    qc.global_phase = math.pi
    return qc

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    for i in range(n):
        qc.h(i)
    oracle = get_oracle(n, L)
    horacle = QuantumCircuit(n)
    for i in range(n):
        horacle.h(i)
    for i in range(10):
        gop = GroverOperator(oracle)
        qc.append(gop, list(range(n)))
        mirror(horacle, n)
    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import ZGate, MCXGate, GroverOperator
import math

def get_oracle(n,L):
    if L == (1<<n):
        qc = QuantumCircuit(n)
        return qc
    numbin = bin(L + (1<<n))[3:]
    qc = QuantumCircuit(n)
    numbin = numbin.rstrip("0")
    print(numbin)
    if numbin[0]== "1":
        qc.x(n-1)
        qc.z(n-1)
        qc.x(n-1)
    else:
        qc.x(n-1)
    for pos, v in enumerate(numbin[1:]):
        pos += 1
        if v=="0":
            qc.x(n-1-pos)
        else:
            qc.x(n-1-pos)
            nn = pos + 1
            circuit=QuantumCircuit(nn)
            circuit.h(nn-1)
            gate = MCXGate(nn-1)
            circuit.append(gate, range(nn))
            circuit.h(nn-1)
            qc.append(circuit.to_gate(), range(n-1,n-2-pos,-1))
            qc.x(n-pos-1)
    for pos, v in enumerate(numbin):
        if v == "0":
            qc.x(n-pos-1)
    qc = qc.decompose()
    return qc

def mirror(oracle: QuantumCircuit, n_qubits: int, barrier: bool = False) -> QuantumCircuit:
    qc = QuantumCircuit(n_qubits)
    qc.append(oracle.inverse(), list(range(n_qubits)))
    qc.x(list(range(n_qubits)))
    qc.h(n_qubits-1)
    qc.mcx(list(range(n_qubits-1)), n_qubits-1)
    qc.h(n_qubits-1)
    qc.x(list(range(n_qubits)))
    qc.append(oracle, list(range(n_qubits)))
    qc.global_phase = math.pi
    return qc

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    for i in range(n):
        qc.h(i)
    oracle = get_oracle(n, L)
    horacle = QuantumCircuit(n)
    for i in range(n):
        horacle.h(i)
    for i in range(10):
        gop = GroverOperator(oracle)
        qc.append(gop, list(range(n)))

    qc = qc.decompose().decompose()
    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import ZGate, MCXGate, GroverOperator
import math

def get_oracle(n,L):
    if L == (1<<n):
        qc = QuantumCircuit(n)
        return qc
    numbin = bin(L + (1<<n))[3:]
    qc = QuantumCircuit(n)
    numbin = numbin.rstrip("0")
    print(numbin)
    if numbin[0]== "1":
        qc.x(n-1)
        qc.z(n-1)
        qc.x(n-1)
    else:
        qc.x(n-1)
    for pos, v in enumerate(numbin[1:]):
        pos += 1
        if v=="0":
            qc.x(n-1-pos)
        else:
            qc.x(n-1-pos)
            nn = pos + 1
            circuit=QuantumCircuit(nn)
            circuit.h(nn-1)
            gate = MCXGate(nn-1)
            circuit.append(gate, range(nn))
            circuit.h(nn-1)
            qc.append(circuit.to_gate(), range(n-1,n-2-pos,-1))
            qc.x(n-pos-1)
    for pos, v in enumerate(numbin):
        if v == "0":
            qc.x(n-pos-1)
    qc = qc.decompose()
    return qc

def mirror(oracle: QuantumCircuit, n_qubits: int, barrier: bool = False) -> QuantumCircuit:
    qc = QuantumCircuit(n_qubits)
    qc.append(oracle.inverse(), list(range(n_qubits)))
    qc.x(list(range(n_qubits)))
    qc.h(n_qubits-1)
    qc.mcx(list(range(n_qubits-1)), n_qubits-1)
    qc.h(n_qubits-1)
    qc.x(list(range(n_qubits)))
    qc.append(oracle, list(range(n_qubits)))
    qc.global_phase = math.pi
    return qc

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    for i in range(n):
        qc.h(i)
    oracle = get_oracle(n, L)
    #horacle = QuantumCircuit(n)
    #for i in range(n):
    #    horacle.h(i)
    for i in range(2*(1<<(n//2))):
        gop = GroverOperator(oracle)
        qc.append(gop, list(range(n)))

    qc = qc.decompose().decompose()
    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import RYGate, HGate, XGate
import math

def dist(L, n):
    if L == 1:
        return [1.0]
    ret = []
    for i in range(n):
        if L < (1<<(i+1)):
            ret.append(max(L - (1<<i),0))
            break
        else:
            if i==0:
                ret.append(2)
            else:
                ret.append(1<<i)

    return [r/L for r in ret if r>0]

def w_state(n_qubits: int, L, control, ctrl_state) -> QuantumCircuit:
    qc = QuantumCircuit(n_qubits)
    seq = dist(L, n_qubits)
    #print(seq)
    RY = RYGate(-math.asin(seq[0]**0.5)*2)
    #qc.append(RY, [0])
    if len(control)>0:
        RY = RY.control(len(control),ctrl_state=ctrl_state)
    qc.append(RY, control + [0])

    for i in range(1, len(seq)):
        RY = RYGate(-math.asin((seq[i]/sum(seq[i:]))**0.5)*2)
        RY = RY.control(len(control)+i,ctrl_state= "0"*i + ctrl_state)
        qc.append(RY, control + [j for j in range(i)] + [i])

    return qc

def solve() -> QuantumCircuit:
    n = 4
    L = 6
    # qc = QuantumCircuit(4)
    # qc.h(0)
    # xg = XGate()
    # xg = xg.control(2,ctrl_state="01")
    # qc.append(xg, [0,1,2])
    # return qc
    dis = dist(L, n)
    binlist = []
    for i in range(len(dis)):
        if ((1<<i) & L) > 0:
            binlist.append(1)
        else:
            binlist.append(0)
    qc = QuantumCircuit(n)
    #return w_state(n,L,[], "")
    b = 1<<(len(binlist)-1)
    l = L
    for i in range(len(binlist)):
        if binlist[-i-1] == 1:
            if i>0:
                ctrls = list(range(len(binlist)))[-i:]
            else:
                ctrls = []
            st = bin(L)[2:2+i]
            #print(ctrls,st,l)
            _qc = w_state(n, l, ctrls, st)
            l -= b
            qc.append(_qc, range(n))
            for j in range(len(binlist)-i-1):
                new_st = st + "".join(["1" if j==k else "0" for k in range(1,len(binlist)-i)][::-1])
                newctrl = [k for k in range(len(binlist) - len(new_st), len(binlist))]
                #print("newst", new_st, newctrl, j)
                if j==0:
                    xg = XGate()
                    xg = xg.control(len(newctrl), ctrl_state=new_st)
                    qc.append(xg, newctrl + [0])
                    hg = HGate()
                    hg = hg.control(len(newctrl), ctrl_state=new_st)
                    qc.append(hg, newctrl + [0])
                else:
                    for k in range(j):
                        hg = HGate()
                        hg = hg.control(len(newctrl), ctrl_state=new_st)
                        qc.append(hg, newctrl + [k])
            #break
        b //= 2
    qc = qc.decompose().decompose()
        #    for k in range(j):
        #         print(j,k)
        #         hg = HGate()
        #         hg = hg.control(len(ctrls)+1, ctrl_state=st+"1")
        #         qc.append(hg, ctrls + [j] + [k])
    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import RYGate, HGate, XGate
import math

def dist(L, n):
    if L == 1:
        return [1.0]
    ret = []
    for i in range(n):
        if L < (1<<(i+1)):
            ret.append(max(L - (1<<i),0))
            break
        else:
            if i==0:
                ret.append(2)
            else:
                ret.append(1<<i)

    return [r/L for r in ret if r>0]

def w_state(n_qubits: int, L, control, ctrl_state) -> QuantumCircuit:
    qc = QuantumCircuit(n_qubits)
    seq = dist(L, n_qubits)
    #print(seq)
    RY = RYGate(-math.asin(seq[0]**0.5)*2)
    #qc.append(RY, [0])
    if len(control)>0:
        RY = RY.control(len(control),ctrl_state=ctrl_state)
    qc.append(RY, control + [0])

    for i in range(1, len(seq)):
        RY = RYGate(-math.asin((seq[i]/sum(seq[i:]))**0.5)*2)
        RY = RY.control(len(control)+i,ctrl_state= "0"*i + ctrl_state)
        qc.append(RY, control + [j for j in range(i)] + [i])

    return qc

def solve(n: int, L: int) -> QuantumCircuit:
    # qc = QuantumCircuit(4)
    # qc.h(0)
    # xg = XGate()
    # xg = xg.control(2,ctrl_state="01")
    # qc.append(xg, [0,1,2])
    # return qc
    dis = dist(L, n)
    binlist = []
    for i in range(len(dis)):
        if ((1<<i) & L) > 0:
            binlist.append(1)
        else:
            binlist.append(0)
    qc = QuantumCircuit(n)
    #return w_state(n,L,[], "")
    b = 1<<(len(binlist)-1)
    l = L
    for i in range(len(binlist)):
        if binlist[-i-1] == 1:
            if i>0:
                ctrls = list(range(len(binlist)))[-i:]
            else:
                ctrls = []
            st = bin(L)[2:2+i]
            #print(ctrls,st,l)
            _qc = w_state(n, l, ctrls, st)
            l -= b
            qc.append(_qc, range(n))
            for j in range(len(binlist)-i-1):
                new_st = st + "".join(["1" if j==k else "0" for k in range(1,len(binlist)-i)][::-1])
                newctrl = [k for k in range(len(binlist) - len(new_st), len(binlist))]
                #print("newst", new_st, newctrl, j)
                if j==0:
                    xg = XGate()
                    xg = xg.control(len(newctrl), ctrl_state=new_st)
                    qc.append(xg, newctrl + [0])
                    hg = HGate()
                    hg = hg.control(len(newctrl), ctrl_state=new_st)
                    qc.append(hg, newctrl + [0])
                else:
                    for k in range(j):
                        hg = HGate()
                        hg = hg.control(len(newctrl), ctrl_state=new_st)
                        qc.append(hg, newctrl + [k])
            #break
        b //= 2
    qc = qc.decompose().decompose()
        #    for k in range(j):
        #         print(j,k)
        #         hg = HGate()
        #         hg = hg.control(len(ctrls)+1, ctrl_state=st+"1")
        #         qc.append(hg, ctrls + [j] + [k])
    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import RYGate, HGate, XGate
import math

def dist(L, n):
    if L == 1:
        return [1.0]
    ret = []
    for i in range(n):
        if L < (1<<(i+1)):
            ret.append(max(L - (1<<i),0))
            break
        else:
            if i==0:
                ret.append(2)
            else:
                ret.append(1<<i)

    return [r/L for r in ret if r>0]

def w_state(n_qubits: int, L, control, ctrl_state) -> QuantumCircuit:
    qc = QuantumCircuit(n_qubits)
    seq = dist(L, n_qubits)
    #print(seq)
    RY = RYGate(-math.asin(seq[0]**0.5)*2)
    #qc.append(RY, [0])
    if len(control)>0:
        RY = RY.control(len(control),ctrl_state=ctrl_state)
    qc.append(RY, control + [0])

    for i in range(1, len(seq)):
        RY = RYGate(-math.asin((seq[i]/sum(seq[i:]))**0.5)*2)
        RY = RY.control(len(control)+i,ctrl_state= "0"*i + ctrl_state)
        qc.append(RY, control + [j for j in range(i)] + [i])

    return qc

def solve(n: int, L: int) -> QuantumCircuit:
    if L == 1:
        return QuantumCircuit(n)
    elif L==2:
        qc = QuantumCircuit(n)
        qc.h(0)
        return qc
    for i in range(2,n+1):
        if L==(1<<i):
            qc = QuantumCircuit(n)
            for j in range(i):
                qc.h(j)
            return qc

    # qc = QuantumCircuit(4)
    # qc.h(0)
    # xg = XGate()
    # xg = xg.control(2,ctrl_state="01")
    # qc.append(xg, [0,1,2])
    # return qc
    L += 1
    dis = dist(L, n)
    binlist = []
    for i in range(len(dis)):
        if ((1<<i) & (L-1)) > 0:
            binlist.append(1)
        else:
            binlist.append(0)
    #print(binlist)

    qc = QuantumCircuit(n)
    #return w_state(n,L,[], "")
    b = 1<<(len(binlist)-1)
    L = L -1
    l = L
    for i in range(len(binlist)):
        if binlist[-i-1] == 1:
            if i>0:
                ctrls = list(range(len(binlist)))[-i:]
            else:
                ctrls = []
            st = bin(L)[2:2+i]
            #print(ctrls,st,l)
            _qc = w_state(n, l, ctrls, st)
            l -= b
            qc.append(_qc, range(n))
            for j in range(len(binlist)-i-1):
                new_st = st + "".join(["1" if j==k else "0" for k in range(1,len(binlist)-i)][::-1])
                newctrl = [k for k in range(len(binlist) - len(new_st), len(binlist))]
                if j>1:
                    new_st = new_st[:-j+1]
                    newctrl = newctrl[j-1:]
                #print("newst", new_st, newctrl, j)
                if j==0:
                    xg = XGate()
                    xg = xg.control(len(newctrl), ctrl_state=new_st)
                    qc.append(xg, newctrl + [0])
                    hg = HGate()
                    hg = hg.control(len(newctrl), ctrl_state=new_st)
                    qc.append(hg, newctrl + [0])
                else:
                    for k in range(j):
                        hg = HGate()
                        hg = hg.control(len(newctrl), ctrl_state=new_st)
                        qc.append(hg, newctrl + [k])
            #break
        b //= 2
    xg = XGate()
    xg = xg.control(n-1, ctrl_state=bin(L + (1<<n))[3:-1])
    qc.append(xg, list(range(1,n)) + [0])
    qc = qc.decompose().decompose()
        #    for k in range(j):
        #         print(j,k)
        #         hg = HGate()
        #         hg = hg.control(len(ctrls)+1, ctrl_state=st+"1")
        #         qc.append(hg, ctrls + [j] + [k])
    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import RYGate, HGate, XGate
import math

def dist(L, n):
    if L == 1:
        return [1.0]
    ret = []
    for i in range(n):
        if L < (1<<(i+1)):
            ret.append(max(L - (1<<i),0))
            break
        else:
            if i==0:
                ret.append(2)
            else:
                ret.append(1<<i)

    return [r/L for r in ret if r>0]

def w_state(n_qubits: int, L, control, ctrl_state) -> QuantumCircuit:
    qc = QuantumCircuit(n_qubits)
    seq = dist(L, n_qubits)
    #print(seq)
    RY = RYGate(-math.asin(seq[0]**0.5)*2)
    #qc.append(RY, [0])
    if len(control)>0:
        RY = RY.control(len(control),ctrl_state=ctrl_state)
    qc.append(RY, control + [0])

    for i in range(1, len(seq)):
        RY = RYGate(-math.asin((seq[i]/sum(seq[i:]))**0.5)*2)
        RY = RY.control(len(control)+i,ctrl_state= "0"*i + ctrl_state)
        qc.append(RY, control + [j for j in range(i)] + [i])

    return qc

def solve(n: int, L: int) -> QuantumCircuit:
    if L == 1:
        return QuantumCircuit(n)
    elif L==2:
        qc = QuantumCircuit(n)
        qc.h(0)
        return qc
    for i in range(2,n+1):
        if L==(1<<i):
            qc = QuantumCircuit(n)
            for j in range(i):
                qc.h(j)
            return qc

    # qc = QuantumCircuit(4)
    # qc.h(0)
    # xg = XGate()
    # xg = xg.control(2,ctrl_state="01")
    # qc.append(xg, [0,1,2])
    # return qc
    L += 1
    dis = dist(L, n)
    binlist = []
    for i in range(len(dis)):
        if ((1<<i) & (L-1)) > 0:
            binlist.append(1)
        else:
            binlist.append(0)
    #print(binlist)

    qc = QuantumCircuit(n)
    #return w_state(n,L,[], "")
    b = 1<<(len(binlist)-1)
    L = L -1
    l = L
    for i in range(len(binlist)):
        if binlist[-i-1] == 1:
            if i>0:
                ctrls = list(range(len(binlist)))[-i:]
            else:
                ctrls = []
            st = bin(L)[2:2+i]
            #print(ctrls,st,l)
            _qc = w_state(n, l, ctrls, st)
            l -= b
            qc.append(_qc, range(n))
            for j in range(len(binlist)-i-1):
                new_st = st + "".join(["1" if j==k else "0" for k in range(1,len(binlist)-i)][::-1])
                newctrl = [k for k in range(len(binlist) - len(new_st), len(binlist))]
                if j>1:
                    new_st = new_st[:-j+1]
                    newctrl = newctrl[j-1:]
                #print("newst", new_st, newctrl, j)
                if j==0:
                    xg = XGate()
                    xg = xg.control(len(newctrl), ctrl_state=new_st)
                    qc.append(xg, newctrl + [0])
                    hg = HGate()
                    hg = hg.control(len(newctrl), ctrl_state=new_st)
                    qc.append(hg, newctrl + [0])
                else:
                    for k in range(j):
                        hg = HGate()
                        hg = hg.control(len(newctrl), ctrl_state=new_st)
                        qc.append(hg, newctrl + [k])
            #break
        b //= 2
    xg = XGate()
    xg = xg.control(n-1, ctrl_state=bin(L + (1<<n))[3:-1])
    qc.append(xg, list(range(1,n)) + [0])
    qc = qc.decompose()
        #    for k in range(j):
        #         print(j,k)
        #         hg = HGate()
        #         hg = hg.control(len(ctrls)+1, ctrl_state=st+"1")
        #         qc.append(hg, ctrls + [j] + [k])
    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import RYGate, HGate, XGate
import math

def dist(L, n):
    if L <= 2:
        return [1.0]
    ret = []
    for i in range(n):
        if L < (1<<(i+1)):
            ret.append(max(L - (1<<i),0))
            break
        else:
            if i==0:
                ret.append(2)
            else:
                ret.append(1<<i)

    return [r/L for r in ret if r>0]

def w_state(n_qubits: int, L, control, ctrl_state) -> QuantumCircuit:
    qc = QuantumCircuit(n_qubits)
    seq = dist(L, n_qubits)

    #print(seq)
    RY = RYGate(-math.asin((seq[-1])**0.5)*2)
    #qc.append(RY, [0])
    if len(control)>0:
        RY = RY.control(len(control),ctrl_state=ctrl_state)
    qc.append(RY, control + [len(seq)-1])

    return qc

def solve(n:int, L:int) -> QuantumCircuit:

    if L == 1:
        return QuantumCircuit(n)
    elif L==2:
        qc = QuantumCircuit(n)
        qc.h(0)
        return qc
    for i in range(2,n+1):
        if L==(1<<i):
            qc = QuantumCircuit(n)
            for j in range(i):
                qc.h(j)
            return qc

    # qc = QuantumCircuit(4)
    # qc.h(0)
    # xg = XGate()
    # xg = xg.control(2,ctrl_state="01")
    # qc.append(xg, [0,1,2])
    # return qc
    L += 1
    dis = dist(L, n)
    binlist = []
    for i in range(len(dis)):
        if ((1<<i) & (L-1)) > 0:
            binlist.append(1)
        else:
            binlist.append(0)
    #print(binlist)

    qc = QuantumCircuit(n)
    #return w_state(n,L,[], "")
    b = 1<<(len(binlist)-1)
    L = L -1
    l = L
    for i in range(len(binlist)):
        if binlist[-i-1] == 1:
            if i>0:
                ctrls = list(range(len(binlist)))[-i:]
            else:
                ctrls = []
            st = bin(L)[2:2+i]
            #print(ctrls,st,l)
            _qc = w_state(n, l, ctrls, st)
            l -= b
            qc.append(_qc, range(n))
            new_st = st + "0"
            newctrl = [k for k in range(len(binlist) - len(new_st), len(binlist))]
            for j in range(len(binlist)-i-1):
                hg = HGate()
                hg = hg.control(len(newctrl), ctrl_state=new_st)
                qc.append(hg, newctrl + [j])
            #break
        b //= 2
    xg = XGate()
    xg = xg.control(n-1, ctrl_state=bin(L + (1<<n))[3:-1])
    qc.append(xg, list(range(1,n)) + [0])
    qc = qc.decompose()
        #    for k in range(j):
        #         print(j,k)
        #         hg = HGate()
        #         hg = hg.control(len(ctrls)+1, ctrl_state=st+"1")
        #         qc.append(hg, ctrls + [j] + [k])
    return qc
'''


'''python
from qiskit import QuantumCircuit
import math
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
import qiskit.circuit.library as qis

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:

    L -= 1

    bits = []
    ones = []
    for i in range(n-1, -1, -1):
        if L & (1<<i) != 0:
            bits += [(i, ones.copy(), 1)]
            ones += [i]
        else:
            bits += [(i, ones.copy(), 0)]

    for target, controls, bit in bits:
        for lsb_ctrl_i in range(len(controls), 0, -1):

            ctrl_subset = controls[0:lsb_ctrl_i]

            ctrl_state = (1<< (lsb_ctrl_i - 1)) - 1
            gate = qis.HGate().control(num_ctrl_qubits=len(ctrl_subset), ctrl_state=ctrl_state)

            qc.append(gate,  ctrl_subset + [target])

        if bit == 1:
            left = 1<<target
            right = (L % left) + 1

            wanted_cos = (left/(left + right))**0.5
            theta = math.acos(wanted_cos)*2

            gate = qis.RXGate(theta=theta)
            if len(controls) != 0:
                gate = gate.control(num_ctrl_qubits=len(controls))
            qc.append(gate, controls + [target])

    return qc
'''


'''python
import math
from qiskit import QuantumCircuit
import qiskit.circuit.library as qis

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:

    L -= 1

    bits = []
    ones = []
    for i in range(n-1, -1, -1):
        if L & (1<<i) != 0:
            bits += [(i, ones.copy(), 1)]
            ones += [i]
        else:
            bits += [(i, ones.copy(), 0)]

    for target, controls, bit in bits:
        for lsb_ctrl_i in range(len(controls), 0, -1):

            ctrl_subset = controls[0:lsb_ctrl_i]

            ctrl_state = (1<< (lsb_ctrl_i - 1)) - 1
            gate = qis.HGate().control(num_ctrl_qubits=len(ctrl_subset), ctrl_state=ctrl_state)

            qc.append(gate,  ctrl_subset + [target])

        if bit == 1:
            left = 1<<target
            right = (L % left) + 1

            wanted_cos = (left/(left + right))**0.5
            theta = math.acos(wanted_cos)*2

            gate = qis.RXGate(theta=theta)
            if len(controls) != 0:
                gate = gate.control(num_ctrl_qubits=len(controls))
            qc.append(gate, controls + [target])

    return qc
'''


'''python
import math
from qiskit import QuantumCircuit
import qiskit.circuit.library as qis

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:

    L -= 1

    bits = []
    ones = []
    for i in range(n-1, -1, -1):
        if L & (1<<i) != 0:
            bits += [(i, len(ones), 1)]
            ones += [i]
        else:
            bits += [(i, len(ones), 0)]

    for target, up_to_i_controls, bit in bits:
        for lsb_ctrl_i in range(up_to_i_controls, 0, -1):

            ctrl_subset = ones[0:lsb_ctrl_i]

            ctrl_state = (1<< (lsb_ctrl_i - 1)) - 1
            gate = qis.HGate().control(num_ctrl_qubits=len(ctrl_subset), ctrl_state=ctrl_state)

            qc.append(gate,  ctrl_subset + [target])

        if bit == 1:
            controls = ones[0:up_to_i_controls]
            left = 1<<target
            right = (L % left) + 1

            wanted_cos = (left/(left + right))**0.5
            theta = math.acos(wanted_cos)*2

            gate = qis.RXGate(theta=theta)
            if len(controls) != 0:
                gate = gate.control(num_ctrl_qubits=len(controls))
            qc.append(gate, controls + [target])

    return qc
'''


'''python
import math
from qiskit import QuantumCircuit
import qiskit.circuit.library as qis

def solve(n: int, L: int) -> QuantumCircuit:
 def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:

    L -= 1

    ones = []

    for target in range(n-1, -1, -1):
        bit = L & (1<<target) != 0

        for lsb_ctrl_i in range(len(ones), 0, -1):

            ctrl_subset = ones[0:lsb_ctrl_i]

            ctrl_state = (1<< (lsb_ctrl_i - 1)) - 1
            gate = qis.HGate().control(num_ctrl_qubits=len(ctrl_subset), ctrl_state=ctrl_state)

            qc.append(gate,  ctrl_subset + [target])

        if bit == 1:
            left = 1<<target
            right = (L % left) + 1

            wanted_cos = (left/(left + right))**0.5
            theta = math.acos(wanted_cos)*2

            gate = qis.RXGate(theta=theta)
            if len(ones) != 0:
                gate = gate.control(num_ctrl_qubits=len(ones))
            qc.append(gate, ones + [target])

            ones.append(target)

    return qc
'''


'''python
import math
from qiskit import QuantumCircuit
import qiskit.circuit.library as qis

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:

    L -= 1

    ones = []

    for target in range(n-1, -1, -1):
        bit = L & (1<<target) != 0

        for lsb_ctrl_i in range(len(ones), 0, -1):

            ctrl_subset = ones[0:lsb_ctrl_i]

            ctrl_state = (1<< (lsb_ctrl_i - 1)) - 1
            gate = qis.HGate().control(num_ctrl_qubits=len(ctrl_subset), ctrl_state=ctrl_state)

            qc.append(gate,  ctrl_subset + [target])

        if bit == 1:
            left = 1<<target
            right = (L % left) + 1

            wanted_cos = (left/(left + right))**0.5
            theta = math.acos(wanted_cos)*2

            gate = qis.RXGate(theta=theta)
            if len(ones) != 0:
                gate = gate.control(num_ctrl_qubits=len(ones))
            qc.append(gate, ones + [target])

            ones.append(target)

    return qc
'''


'''python
import math
from qiskit import QuantumCircuit
import qiskit.circuit.library as qis
import numpy as np

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:

    L -= 1

    ones = []
    one_count = 0

    inds = np.arange(n)
    lefts = np.vectorize(lambda x: 1<<x)(inds)
    wanted_coss = np.vectorize(lambda left: (left / (left + ((L%left) + 1))) ** 0.5)(lefts)
    thetas = np.vectorize(lambda w: math.acos(w) * 2)(wanted_coss)

    for target in range(n-1, -1, -1):
        bit = L & (1<<target) != 0

        for lsb_ctrl_i in range(len(ones), 0, -1):

            ctrl_subset = ones[0:lsb_ctrl_i]

            ctrl_state = (1<< (lsb_ctrl_i - 1)) - 1
            gate = qis.HGate().control(num_ctrl_qubits=len(ctrl_subset), ctrl_state=ctrl_state)

            qc.append(gate, ctrl_subset + [target], copy=False)

        if bit == 1:
            theta = thetas[target]

            gate = qis.RXGate(theta=theta)
            if one_count != 0:
                gate = gate.control(num_ctrl_qubits=one_count)

            qc.append(gate, ones + [target], copy=False)

            ones.append(target)
            one_count += 1

    return qc
'''


'''python
import math
from qiskit import QuantumCircuit
from qiskit.circuit.library import HGate, RXGate
import numpy as np

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:

    L -= 1

    ones = []
    one_count = 0

    inds = np.arange(n)
    lefts = np.vectorize(lambda x: 1<<x)(inds)
    wanted_coss = np.vectorize(lambda left: (left / (left + ((L%left) + 1))) ** 0.5)(lefts)
    thetas = np.vectorize(lambda w: math.acos(w) * 2)(wanted_coss)

    for target in range(n-1, -1, -1):
        bit = L & (1<<target) != 0

        for lsb_ctrl_i in range(one_count, 0, -1):

            ctrl_subset = ones[0:lsb_ctrl_i]

            ctrl_state = (1<< (lsb_ctrl_i - 1)) - 1
            gate = HGate().control(num_ctrl_qubits=lsb_ctrl_i, ctrl_state=ctrl_state, annotated=True)

            qc.append(gate, ctrl_subset + [target], copy=False)

        if bit == 1:
            theta = thetas[target]

            gate = RXGate(theta=theta)
            if one_count != 0:
                gate = gate.control(num_ctrl_qubits=one_count, annotated=True)

            qc.append(gate, ones + [target], copy=False)

            ones.append(target)
            one_count += 1

    return qc
'''


'''python
import math
from qiskit import QuantumCircuit
from qiskit.circuit.library import HGate, RXGate
import numpy as np

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:

    L -= 1

    ones = []
    one_count = 0

    inds = np.arange(n)
    lefts = np.vectorize(lambda x: 1<<x)(inds)
    wanted_coss = np.vectorize(lambda left: (left / (left + ((L%left) + 1))) ** 0.5)(lefts)
    thetas = np.vectorize(lambda w: math.acos(w) * 2)(wanted_coss)

    CHs = [HGate()] + [HGate().control(num_ctrl_qubits=i, ctrl_state=(1<<(i-1))-1)  for i in range(1, n)]

    for target in range(n-1, -1, -1):
        bit = L & (1<<target) != 0

        for lsb_ctrl_i in range(len(ones), 0, -1):

            ctrl_subset = ones[0:lsb_ctrl_i]

            gate = CHs[lsb_ctrl_i]

            qc.append(gate, ctrl_subset + [target])

        if bit == 1:
            theta = thetas[target]

            gate = RXGate(theta=theta)
            if one_count != 0:
                gate = gate.control(num_ctrl_qubits=one_count)

            qc.append(gate, ones + [target], copy=False)

            ones.append(target)
            one_count += 1

    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import HGate, RYGate
import math

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:
    M = L
    i = n-1
    if (L>>i)&1 == 0:
        qc.x(i)
    else:
        theta = -2*math.acos(math.sqrt(2**i/M))
        qc.x(i)
        qc.ry(theta,i)
        CH = HGate().control(n-i)
        for j in range(i):
            qc.append(CH,list(range(n-1,i-1,-1))+[j])
        qc.x(i)
        M -= 2**i
    for i in range(n-2,-1,-1):
        if (L>>i)&1 == 0:
            qc.x(i)
        else:
            theta = -2*math.acos(math.sqrt(2**i/M))
            qc.x(i)
            qc.append(RYGate(theta).control(n-i-1),range(n-1,i-1,-1))
            CH = HGate().control(n-i)
            for j in range(i):
                qc.append(CH,list(range(n-1,i-1,-1))+[j])
            qc.x(i)
            M -= 2**i
        qc_copy = qc.copy()
        for j in range(n-1,i-1,-1):
            if (L>>j)&1 == 0:
                qc_copy.x(j)
    for i in range(n-1,-1,-1):
        if (L>>i)&1 == 0:
            qc.x(i)
    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import HGate, RYGate
import math

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:
    if L==(1<<n):
        for i in range(n):
            qc.h(i)
    else:
        M = L
        i = n-1
        if (L>>i)&1 == 0:
            qc.x(i)
        else:
            theta = -2*math.acos(math.sqrt(2**i/M))
            qc.x(i)
            qc.ry(theta,i)
            CH = HGate().control(n-i)
            for j in range(i):
                qc.append(CH,list(range(n-1,i-1,-1))+[j])
            qc.x(i)
            M -= 2**i
        for i in range(n-2,-1,-1):
            if (L>>i)&1 == 0:
                qc.x(i)
            else:
                theta = -2*math.acos(math.sqrt(2**i/M))
                qc.x(i)
                qc.append(RYGate(theta).control(n-i-1),range(n-1,i-1,-1))
                CH = HGate().control(n-i)
                for j in range(i):
                    qc.append(CH,list(range(n-1,i-1,-1))+[j])
                qc.x(i)
                M -= 2**i
            qc_copy = qc.copy()
            for j in range(n-1,i-1,-1):
                if (L>>j)&1 == 0:
                    qc_copy.x(j)
        for i in range(n-1,-1,-1):
            if (L>>i)&1 == 0:
                qc.x(i)
    return qc
'''


'''python
def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:
    if L == 2**n:
        for i in range(n):
            qc.h(i)
    else:
        L_code = format(L, f'0{n}b')
        m = [n-1-i for i in range(n) if L_code[i] == "1"]
        l = [L]
        for i in range(len(m)-1):
            l.append(l[-1]-2**m[i])
        qc.x(m[0])
        for i in range(len(m)-1):
            split_one_hot(qc,m[i],m[i+1],2**m[i]/l[i])
        for i in range(n-1,-1,-1):
            if i in m and i !=0:
                qc.append(multi_ch(i,n), qargs=range(n-1,-1,-1))
            qc.x(i)
        for i in range(n-1,-1,-1):
            if L_code[i] == "0":
                if i != 0:
                    qc.append(XGate().control(i),qargs=range(n-1,n-2-i,-1))
                else:
                    qc.x(n-1-i)
        print(m,l)
    return qc

def split_one_hot(qc,m1,m2,l):
    print(m1,m2,l)
    qc.cry(2*math.acos(math.sqrt(l)),m1,m2)
    qc.cx(m2,m1)

def multi_ch(i,n):
    # Hゲートだけのサブ回路作成
    qch = QuantumCircuit(i)
    for j in range(i):
        qch.h(j)

    # ゲート化 → 多重制御化
    h_gate = qch.to_gate()
    print(n-i-1)
    controlled_h_gate = h_gate.control(n-i)
    return controlled_h_gate
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import XGate
import math

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # Write your code here:
    if L == 2**n:
        for i in range(n):
            qc.h(i)
    else:
        L_code = format(L, f'0{n}b')
        m = [n-1-i for i in range(n) if L_code[i] == "1"]
        l = [L]
        for i in range(len(m)-1):
            l.append(l[-1]-2**m[i])
        qc.x(m[0])
        for i in range(len(m)-1):
            split_one_hot(qc,m[i],m[i+1],2**m[i]/l[i])
        for i in range(n-1,-1,-1):
            if i in m and i !=0:
                qc.append(multi_ch(i,n), qargs=range(n-1,-1,-1))
            qc.x(i)
        for i in range(n-1,-1,-1):
            if L_code[i] == "0":
                if i != 0:
                    qc.append(XGate().control(i),qargs=range(n-1,n-2-i,-1))
                else:
                    qc.x(n-1-i)
        print(m,l)
    return qc

def split_one_hot(qc,m1,m2,l):
    print(m1,m2,l)
    qc.cry(2*math.acos(math.sqrt(l)),m1,m2)
    qc.cx(m2,m1)

def multi_ch(i,n):
    # Hゲートだけのサブ回路作成
    qch = QuantumCircuit(i)
    for j in range(i):
        qch.h(j)

    # ゲート化 → 多重制御化
    h_gate = qch.to_gate()
    print(n-i-1)
    controlled_h_gate = h_gate.control(n-i)
    return controlled_h_gate
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import HGate
from qiskit.circuit.library import RYGate
import math
def solve(n: int, L: int) -> QuantumCircuit:
  qc = QuantumCircuit(n)
  L2 = L
  for i in range(n - 1, -1, -1):
    if L2 > (1 << i):
      print(i)
      for j in range(i + 1, n):
        if (((L - 1) >> j) & 1) == 0:
          qc.x(j)
      theta = math.atan2(math.sqrt(L2 - (1 << i)), math.sqrt(1 << i)) * 2
      if i == n - 1:
        qc.ry(theta, n - 1)
      else:
        qc.append(RYGate(theta).control(n - 1 - i), list(range(i + 1, n)) + [i])
      qc.x(i)
      for j in range(i):
        qc.append(HGate().control(n - i), list(range(i, n)) + [j])
      qc.x(i)
      L2 = L2 - (1 << i)
      for j in range(i + 1, n):
        if (((L - 1) >> j) & 1) == 0:
          qc.x(j)
  return qc
'''


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

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # 量子状態の次元は 2^n なので、状態ベクトルの長さは 2**n となる
    dim = 2 ** n

    # 状態ベクトルを初期化
    # i = 0, 1, ..., L-1 の各成分に 1/sqrt(L) を設定し、
    # それ以外の成分は 0 とする。
    # これにより、目的の状態
    # |ψ⟩ = (1/√L) (|0⟩ + |1⟩ + ... + |L-1⟩)
    # が得られる
    state = [0.0] * dim
    amp = 1 / np.sqrt(L)
    for i in range(L):
        state[i] = amp

    # 初期状態から目的の状態へ初期化する
    # Qiskit ではデフォルトでリトルエンディアンとなっているため、
    # list(range(n)) で各量子ビットを指定する
    qc.initialize(state, list(range(n)))

    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library import StatePreparation
import numpy as np

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)

    # 2^n 次元の状態ベクトルを用意する．
    # 添字 i = 0,1,...,L-1 に対して振幅 1/sqrt(L) を与え，
    # i >= L の部分は 0 とする．
    dim = 2 ** n
    state = np.zeros(dim, dtype=complex)
    amp = 1 / np.sqrt(L)
    for i in range(L):
        state[i] = amp

    # StatePreparation クラスは内部で Möttönen型のアルゴリズムにより
    # 標準ゲート（Ry, Rz, CNOT など）を用いた回路へ分解される．
    # これにより，Initialize などの禁止ゲートを使うことなく目的の状態を作る．
    sp = StatePreparation(state)
    qc.append(sp, qc.qubits)

    return qc
'''


'''python
from qiskit import QuantumCircuit
from qiskit.circuit.library.standard_gates import RYGate
import math
import itertools

def solve(n: int, L: int) -> QuantumCircuit:
    qc = QuantumCircuit(n)
    # 量子ビットの番号は 0～n-1，
    # リトルエンディアンでは整数値は ∑_{j=0}^{n-1} 2^j * (qubit j の値) として読む

    # ここでは，最も重みの大きい qubit（番号 n-1）から順に回転を設定する
    for k in range(n-1, -1, -1):
        # 上位ビットとして制御する qubit の集合は {q_{k+1},...,q_{n-1}}
        control_indices = list(range(k+1, n))
        # 制御対象の上位ビットの割り当て（分岐）をすべて走査
        for prefix in itertools.product([0, 1], repeat=len(control_indices)):
            # prefix に対応して，上位ビットが取る値により整数値への寄与は
            # P = ∑_{j in control_indices} (bit_j * 2^j)
            P = 0
            for ctrl, bit in zip(control_indices, prefix):
                P += bit * (2 ** ctrl)
            # 現在決定する qubitは q_k の重み 2^k で寄与する
            # 下位（q_{0}～q_{k-1}）で作れる状態数は 2^k 個
            # よって，q_k に 0 を割り当てた場合の有効状態数は
            if P >= L:
                N0 = 0
            else:
                N0 = min(2 ** k, L - P)
            # q_k に 1 を割り当てた場合は，寄与が 2^k 加わるので
            if P + (2 ** k) >= L:
                N1 = 0
            else:
                N1 = min(2 ** k, L - (P + (2 ** k)))
            N_total = N0 + N1
            # もしこの分岐で有効な状態がなければスキップ
            if N_total == 0:
                continue
            # 回転角は，理想的には
            # cos(θ/2) = √(N0/(N0+N1))，すなわち θ = 2·arccos(√(N0/N_total))
            # ただし，N0=0 のときは θ = π，また N1=0 のときは θ = 0 とする
            if N0 == 0:
                theta = math.pi
            elif N1 == 0:
                theta = 0.0
            else:
                theta = 2 * math.acos(math.sqrt(N0 / N_total))
            # 角度が 0 ならゲート不要
            if abs(theta) < 1e-10:
                continue

            # 制御付き RY ゲートを作成
            base_gate = RYGate(theta)
            num_controls = len(control_indices)
            if num_controls > 0:
                controlled_gate = base_gate.control(num_controls)
                # デフォルトでは制御は「|1>」の場合に作用するため，
                # 制御すべき値が 0 のときは X ゲートで反転させる
                for ctrl, bit in zip(control_indices, prefix):
                    if bit == 0:
                        qc.x(ctrl)
                # 制御 qubit（上位ビット）＋対象 qubit q_k の順番で追加
                qc.append(controlled_gate, control_indices + [k])
                for ctrl, bit in zip(control_indices, prefix):
                    if bit == 0:
                        qc.x(ctrl)
            else:
                # 制御 qubitがない場合は単純に RY ゲートを適用
                qc.append(base_gate, [k])
    return qc
'''