CodeEff/ECCO huggingface dataset:
# Original solution
# -*- using utf8 -*-
import sys
inputlinevec = sys.stdin.readline().strip().split(' ')
n = int(inputlinevec[0])
x = int(inputlinevec[1])
m = int(inputlinevec[2])

sum_res = x
crcle_list = list()
crcle_idx = 0
pre_a = x

for idx in range(1, n):
    #a范围在0-m之间，不会无限递增，因此很大概率会重复
    #a * a % m这种单变量的式子，一旦a出现了之前出现过的值
    #后续就会出现重复的序列，然后循环
    this_a = (pre_a * pre_a) % m
    pre_a = this_a
    
    if this_a not in crcle_list:
        crcle_list.append(this_a)
        sum_res = sum_res + this_a
    else:
        crcle_step = len(crcle_list) - crcle_list.index(this_a)
        remain_crcle = int((n - idx) / crcle_step)
        remain_crcle_tail = int((n - idx) % crcle_step)
        
        crcle_sum = 0
        crcle_sum_tail = 0
        for a_item in crcle_list[crcle_list.index(this_a):]:
            crcle_sum = crcle_sum + a_item
            remain_crcle_tail = remain_crcle_tail - 1
            if remain_crcle_tail == 0:
                crcle_sum_tail = crcle_sum
        sum_res = sum_res + (remain_crcle * crcle_sum) + crcle_sum_tail
        break
        
    
print(sum_res)

# Optimized solution
# -*- using utf8 -*-
import sys
inputlinevec = sys.stdin.readline().strip().split(' ')
n = int(inputlinevec[0])
x = int(inputlinevec[1])
m = int(inputlinevec[2])

sum_res = x
crcle_dict = dict()
crcle_list = list()
crcle_idx = 0
pre_a = x

for idx in range(1, n):
    #a范围在0-m之间，不会无限递增，因此很大概率会重复
    #a * a % m这种单变量的式子，一旦a出现了之前出现过的值
    #后续就会出现重复的序列，然后循环
    this_a = (pre_a * pre_a) % m
    pre_a = this_a
    
    if this_a not in crcle_dict:
        crcle_dict[this_a] = 1
        crcle_list.append(this_a)
        sum_res = sum_res + this_a
    else:
        crcle_step = len(crcle_list) - crcle_list.index(this_a)
        remain_crcle = int((n - idx) / crcle_step)
        remain_crcle_tail = int((n - idx) % crcle_step)
        
        crcle_sum = 0
        crcle_sum_tail = 0
        for a_item in crcle_list[crcle_list.index(this_a):]:
            crcle_sum = crcle_sum + a_item
            remain_crcle_tail = remain_crcle_tail - 1
            if remain_crcle_tail == 0:
                crcle_sum_tail = crcle_sum
        sum_res = sum_res + (remain_crcle * crcle_sum) + crcle_sum_tail
        break
    
print(sum_res)
# Original solution
N, X, M = list(map(int, input().split()))

if N == 1:
    print(X)
    exit()

A = [-1] * (10**5 + 1)
A[1] = X

# %M は答えをMOD Mにしなさいといってくれているだけ
# M はたかだか10^5なので10^5繰り返すとどこかで循環する。循環するまで繰り返す。
S = set([X])
i = 2
while True:
    A[i] = ((A[i - 1])**2) % M
    if A[i] in S:
        break
    S.add(A[i])
    i += 1
# i -= 1
# print(f'{A[:20]=}, {S=}, {i=}')

end_idx = i - 1
start_idx = 0
for start_idx in range(i):
    if A[start_idx] == A[i]:
        break

num_circles = end_idx - start_idx + 1
# print(f'{start_idx=}, {end_idx=}, {num_circles=}')

A[0] = 0
if start_idx > N:
    ans = sum(A[:N + 1])
    print(ans)
    exit()

# print(f'{A[:20]=}')
# print(f'{A[:start_idx]=}')
v1 = sum(A[:start_idx])

remain_N = N - start_idx + 1
# print(f'{remain_N=}')

div, mod = divmod(remain_N, num_circles)
# print(f'{div=}, {mod=}')
# print(f'{A[start_idx:end_idx + 1]=}')
sum_circles = sum(A[start_idx:end_idx + 1])
# print(f'{sum_circles=}')

v2 = sum_circles * div

if mod == 0:
    v3 = 0
else:
    # print(f'{A[start_idx:start_idx + mod]=}')
    v3 = sum(A[start_idx:start_idx + mod])

ans = v1 + v2 + v3
print(ans)


# Optimized solution
N, X, M = list(map(int, input().split()))

I = [-1] * M
A = []
total = 0
while (I[X] == -1):
    A.append(X)
    I[X] = len(A)
    total += X
    X = (X * X) % M

# print(f'{A=}')
# print(f'{I[:20]=}')
# print(f'{total=}')
# print(f'{X=}, {I[X]=}')

c = len(A) - I[X] + 1
s = sum(A[I[X] - 1:])
# print(f'{c=}, {s=}')
ans = 0
if N < len(A):
    ans += sum(A[:N])
else:
    ans += total
    N -= len(A)
    ans += s * (N // c)
    N %= c
    ans += sum(A[I[X] - 1:I[X] - 1 + N])
print(ans)
# Original solution
""" E
    https://atcoder.jp/contests/abc173/tasks/abc173_e
"""
import sys
import math
from functools import reduce

def readString():
    return sys.stdin.readline()

def readInteger():
    return int(readString())

def readStringSet(n):
    return sys.stdin.readline().split(" ")[:n]

def readIntegerSet(n):
    return list(map(int, readStringSet(n)))

def readIntegerMatrix(n, m):
    return reduce(lambda acc, _: acc + [readIntegerSet(m)], list(range(0, n)), [])

def main(N, X, M):
    A = X
    l = [A]
    i = -1
    for _ in range(1, M):
        A = (A * A) % M if M > 0 else 0
        if A in l:
            i = l.index(A)
            break
        else:
            l.append(A)

    if i == -1:
        return sum(l)
    else:
        s1 = sum(l[:i])
        len_repeat = len(l) - i
        s2 = sum(l[i:])

        return s1 + int((N-i)/len_repeat) * s2 + sum(l[i:(N-i)%len_repeat+i])

if __name__ == "__main__":
    _N, _X, _M = readIntegerSet(3)

    print((main(_N, _X, _M)))

# Optimized solution
""" E
    https://atcoder.jp/contests/abc173/tasks/abc173_e
"""
import sys
import math
from functools import reduce

def readString():
    return sys.stdin.readline()

def readInteger():
    return int(readString())

def readStringSet(n):
    return sys.stdin.readline().split(" ")[:n]

def readIntegerSet(n):
    return list(map(int, readStringSet(n)))

def readIntegerMatrix(n, m):
    return reduce(lambda acc, _: acc + [readIntegerSet(m)], list(range(0, n)), [])

def main(N, X, M):
    A = X
    m = {A: A}
    i = -1
    for j in range(1, M):
        A = (A * A) % M if M > 0 else 0
        if A in m:
            i = list(m.keys()).index(A)
            break
        else:
            m[A] = A

    if i == -1:
        return sum(m.values())
    else:
        l = list(m.values())
        s1 = sum(l[:i])
        len_repeat = len(l) - i
        s2 = sum(l[i:])

        return s1 + int((N-i)/len_repeat) * s2 + sum(l[i:(N-i)%len_repeat+i])

if __name__ == "__main__":
    _N, _X, _M = readIntegerSet(3)

    print((main(_N, _X, _M)))
# Original solution
import sys
N, X, M = list(map(int, input().split()))
if N == 1:
  print(X)
  sys.exit()

ans = 0
ans += X - (X%M)
X %= M

def fun(x):
  return (x * x) % M

appear_list = [X]
appear_set = {X}

x = X
i_0 = 1
sum_0 = x

while fun(x) not in appear_set:
  x = fun(x)
  appear_list.append(x)
  appear_set.add(x)
  sum_0 += x
  i_0 += 1
  #print(appear_list, x, fun(x))
  #print(i_0, N, appear_set)
  if i_0 == N:
    print((ans + sum_0))
    sys.exit()

ans += sum_0
N -= i_0

x = fun(x)
appear_set_2 = {x}
sum_1 = x
sum_list = [0,x]
i_1 = 1
while fun(x) not in appear_set_2:
  x = fun(x)
  appear_set_2.add(x)
  sum_1 += x
  sum_list.append(sum_1)
  i_1 += 1
  
sum_0 -= sum_1
i_0 -= i_1

#print(N % i_1)
ans += sum_1 * (N // i_1) + sum_list[(N % i_1)]

print(ans)



  
  
  


# Optimized solution
import sys

N, X, M = list(map(int, input().split()))

if N == 1: #例外
  print(X)
  sys.exit()

ans = 0
ans += X - (X%M) #XがMより大きい場合、超過分を先に計上する。
X %= M #これで 0 <= X <= M-1 が成り立つようにできた。

def fun(x): #問題の関数を用意（いちいち中身を書いていると面倒くさいため）
  return (x * x) % M

appear_set = {X} #すでに現れた数を格納する


i_0 = 1 #今までに調べた個数。現在は「X」の1つだけ。
x = X #このxに何度も関数funを作用させる
sum_0 = x #現在までの和

# ①：すでに出現したことのある数が現れるまで、ループを回す。
#  　この途中で目標回数Nに到達するなら、その時点で答えを出力する(31-33行目)。
while fun(x) not in appear_set: #次のxが初めて現れる数なら続ける。
  x = fun(x) #xにfunを作用
  appear_set.add(x) #xを「現れたものリスト」に格納
  sum_0 += x #和の更新
  i_0 += 1   #調べた個数の更新
  
  if i_0 == N: #目標回数に到達したら、その時点で答えを出力して終了。
    print((ans + sum_0))
    sys.exit()

# 現在、xには系列に初めて現れた最後の数が入っている。
# 次の数であるfun(x)は、前に現れたことのある数。したがって、ここからループが始まる。
# 整理のため、ここまでの和を計上し、残り回数も減らしておく。
ans += sum_0
N -= i_0

# ②：ループの性質を調べるため、もう一度ループを回したい。
#　欲しいものは3つ。
#   1.ループ１週の和
#   2.ループの途中までの和を記録した配列。
#   3.ループの長さ

#　以下、先ほどと異なる部分を中心に説明する。
x = fun(x) # 次の数へ行く(ループの最初の数)
appear_set_2 = {x} 
sum_1 = x        # 欲しいもの1。ループ１周の和を記録する。
sum_list = [0,x] # 欲しいもの2。i番目の要素がi番目までの数までの和を示すよう、この後要素を追加する。
i_1 = 1 # すでに調べた個数をカウントする。現在は「x」の1個だけ。
# このi_1が、最終的にループの長さ(欲しいもの3)になる。

# 以下、60行目以外の処理は先ほどと同様。
while fun(x) not in appear_set_2:
  x = fun(x)
  appear_set_2.add(x)
  sum_1 += x 
  sum_list.append(sum_1) #途中までの和を記録。
  i_1 += 1
  
# ③：上で求めた３つの情報（一周の和sum_1, 途中までの和の記録sum_list, ループ長i_1）
#    を使って答えを求める。
ans += sum_1 * (N // i_1) + sum_list[(N % i_1)]

print(ans)
# Original solution
N, X, M = list(map(int, input().split()))
ind = 0
l = [X]
while True:
  t = l[-1] ** 2 % M
  if t not in l:
    l.append(t)
  else:
    ind = l.index(t)
    break
S = sum(l[ind:])
L = len(l)
ans = 0
if N <= L:
  ans = sum(l[:N])
else:
  ans = sum(l)
  N -= L
  ans += S * (N // (L - ind))
  ans += sum(l[ind:ind+(N % (L - ind))])
print(ans)

# Optimized solution
N, X, M = list(map(int, input().split()))
checklist = [True] * 100000
ind = 0
l = [X]
while True:
  t = l[-1] ** 2 % M
  if checklist[t]:
    l.append(t)
    checklist[t] = False
  else:
    ind = l.index(t)
    break
S = sum(l[ind:])
L = len(l)
ans = 0
if N <= L:
  ans = sum(l[:N])
else:
  ans = sum(l)
  N -= L
  ans += S * (N // (L - ind))
  ans += sum(l[ind:ind+(N % (L - ind))])
print(ans)
# Original solution
N,X,M=list(map(int,input().split()))

seen=[-2]*M
seen[X]
A=[X]
i=1
while(i<N):
    T=A[-1]**2%M
    if seen[T]!=-2:
        Roop=i-seen[T]
        Left,Right=seen[T],i
        break
    A.append(T)
    seen[T]=i
    i+=1

if i==N:
    print((sum(A)))
    exit()

Roopsum=0
for i in range(Left,Right):
    Roopsum+=A[i]

Rest=N-len(A)

ans=sum(A)

ans+=Rest//Roop*Roopsum

for i in range(Rest%Roop):
    ans+=T
    T=T**2%M
print(ans)

# Optimized solution
N,X,M=list(map(int,input().split()))

i=1
A=[X]
seen=[-1]*M
seen[X]=0
while(i<N):
    T=A[-1]**2%M
    #seen[T]~i-1までがループになっている
    if seen[T]!=-1:
        Roop=i-seen[T]
        Left,Right=seen[T],i
        break
    seen[T]=i
    A.append(T)
    i+=1

if i==N:
    print((sum(A)))
    exit()

ans=sum(A)
RoopSum=0
for i in range(Left,Right):
    RoopSum+=A[i]

Rest=N-len(A)

ans+=Rest//Roop*RoopSum

for i in range(Rest%Roop):
    ans+=T
    T=T**2%M
print(ans)
# Original solution
#import sys
#print(sys.maxsize)
N,X,M=list(map(int,input().split()))
#table=list(range(M))
#for i in range(M):
 #   table[i]=((table[i]%M)**2)%M
#print(table[471])
start=X%M
rireki=list()
rireki.append(start)
ss=0
for j in range(1,N):
    start=(start**2)%M
    if start in rireki:
        ss=rireki.index(start)
        break
    else:
        rireki.append(start)
nn=len(rireki)
rep=(N-ss)//(nn-ss)
nokori=N-ss-rep*(nn-ss)
loop=rireki[ss:]
#print(nn)
#print(rep)
#print(sum(loop))
#print(ss)
#print(nokori+rep*(nn-ss)+ss)
if 0 in rireki:
    goukei=sum(rireki)
else:
    goukei=rep*sum(loop)+sum(rireki[:ss])+sum(loop[:nokori])
print(goukei)

# Optimized solution
#import sys
#print(sys.maxsize)
N,X,M=list(map(int,input().split()))
#table=list(range(M))
#for i in range(M):
 #   table[i]=((table[i]%M)**2)%M
#print(table[471])
start=X%M
rset=set()
rireki=list()
rset.add(start)
rireki.append(start)
ss=0
for j in range(1,M+1):
    start=(start**2)%M
    if start in rset:
        ss=rireki.index(start)
        break
    else:
        rireki.append(start)
        rset.add(start)
nn=len(rireki)
rep=(N-ss)//(nn-ss)
nokori=N-ss-rep*(nn-ss)
loop=rireki[ss:]
#print(nn)
#print(rep)
#print(sum(loop))
#print(ss)
#print(nokori+rep*(nn-ss)+ss)
if 0 in rireki:
    goukei=sum(rireki)
else:
    goukei=rep*sum(loop)+sum(rireki[:ss])+sum(loop[:nokori])
print(goukei)
# Original solution
N,X,M=list(map(int,input().split()))
table=[X]

ans=X

for i in range(N-1):
    nx=table[i]**2
    nx%=M
    if nx in table:
        first=table.index(nx)
        oneloop=i+1-first
        rest=N-i-1
        loops=rest//oneloop
        totalofoneloop=sum(table[first:])
        ans+=totalofoneloop*loops
        remain=rest%oneloop
        ans+=sum(table[first:first+remain])
        print(ans)
        exit()
    else:
        table.append(nx)
        ans+=nx
 

print(ans)

# Optimized solution
N,X,M=list(map(int,input().split()))
table=[X]
visited=[-1]*M
visited[X]=1

ans=X

for i in range(N-1):
    nx=table[i]**2
    nx%=M
    if visited[nx]>0:
        first=table.index(nx)
        oneloop=i+1-first
        rest=N-i-1
        loops=rest//oneloop
        totalofoneloop=sum(table[first:])
        ans+=totalofoneloop*loops
        remain=rest%oneloop
        ans+=sum(table[first:first+remain])
        print(ans)
        exit()
    else:
        table.append(nx)
        visited[nx]=1
        ans+=nx
 

print(ans)
# Original solution
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    N, X, M = list(map(int, readline().split()))

    n = 1
    P = 1
    while n < N:
        n *= 2
        P += 1

    pos = [[0] * M for _ in range(P)]
    value = [[0] * M for _ in range(P)]

    for r in range(M):
        pos[0][r] = r * r % M
        value[0][r] = r

    for p in range(P - 1):
        for r in range(M):
            pos[p + 1][r] = pos[p][pos[p][r]]
            value[p + 1][r] = value[p][r] + value[p][pos[p][r]]

    ans = 0
    cur = X % M
    for p in range(P):
        if N & (1 << p):
            ans += value[p][cur]
            cur = pos[p][cur]

    print(ans)
    return


if __name__ == '__main__':
    main()


# Optimized solution
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    N, X, M = list(map(int, readline().split()))

    P = N.bit_length()
    pos = [[0] * M for _ in range(P)]
    value = [[0] * M for _ in range(P)]

    for r in range(M):
        pos[0][r] = r * r % M
        value[0][r] = r

    for p in range(P - 1):
        for r in range(M):
            pos[p + 1][r] = pos[p][pos[p][r]]
            value[p + 1][r] = value[p][r] + value[p][pos[p][r]]

    ans = 0
    cur = X
    for p in range(P):
        if N & (1 << p):
            ans += value[p][cur]
            cur = pos[p][cur]

    print(ans)
    return


if __name__ == '__main__':
    main()
# Original solution
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    N, X, M = list(map(int, readline().split()))

    P = N.bit_length()
    pos = [[0] * M for _ in range(P)]
    value = [[0] * M for _ in range(P)]

    for r in range(M):
        pos[0][r] = r * r % M
        value[0][r] = r

    for p in range(P - 1):
        for r in range(M):
            pos[p + 1][r] = pos[p][pos[p][r]]
            value[p + 1][r] = value[p][r] + value[p][pos[p][r]]

    ans = 0
    cur = X
    for p in range(P):
        if N & (1 << p):
            ans += value[p][cur]
            cur = pos[p][cur]

    print(ans)
    return


if __name__ == '__main__':
    main()


# Optimized solution
import sys

readline = sys.stdin.readline


def main():
    N, X, M = list(map(int, readline().split()))

    P = N.bit_length()
    pos = [[0] * M for _ in range(P)]
    value = [[0] * M for _ in range(P)]

    for r in range(M):
        pos[0][r] = r * r % M
        value[0][r] = r

    for p in range(P - 1):
        for r in range(M):
            pos[p + 1][r] = pos[p][pos[p][r]]
            value[p + 1][r] = value[p][r] + value[p][pos[p][r]]

    ans = 0
    cur = X
    for p in range(P):
        if N & (1 << p):
            ans += value[p][cur]
            cur = pos[p][cur]

    print(ans)
    return


if __name__ == '__main__':
    main()
# Original solution
n,x,m=list(map(int,input().split()))
ans=x
a=[x]
if n==1:
  print(ans)
else:
  for i in range(2,n+1):
    tmp=a[-1]**2%m
    if tmp not in a:
      a.append(tmp)
      ans+=tmp
    else:
      t=a.index(tmp)
      if len(a)-t>=n-i+1:
        ans+=sum(a[t:t+n-i+1])
        break
      else:
        t=a.index(tmp)
        tmp_a=(n-i+1)//(len(a)-t)
        tmp_b=(n-i+1)-(len(a)-t)*tmp_a
        ans+=sum(a[t:])*tmp_a+sum(a[t:t+tmp_b])
        break
  print(ans)

# Optimized solution
n,x,m=list(map(int,input().split()))
ans=x
a=[x]
d={}
d[x]=1
if n==1:
  print(ans)
else:
  for i in range(2,n+1):
    tmp=a[-1]**2%m
    if d.get(tmp,0)==0:
      a.append(tmp)
      d[tmp]=1
      ans+=tmp
    else:
      t=a.index(tmp)
      if len(a)-t>=n-i+1:
        ans+=sum(a[t:t+n-i+1])
        break
      else:
        t=a.index(tmp)
        tmp_a=(n-i+1)//(len(a)-t)
        tmp_b=(n-i+1)-(len(a)-t)*tmp_a
        ans+=sum(a[t:])*tmp_a+sum(a[t:t+tmp_b])
        break
  print(ans)
# Original solution
n, x, m = list(map(int, input().split()))

ans = []
flag = False
for i in range(n):
    if x in ans:
        v = x
        flag = True
        break
    ans.append(x)
    x = x**2 % m
if flag:
    p = ans.index(v)
    l = len(ans) - p
    d, e = divmod(n-p, l)
    print((sum(ans[:p]) + d*sum(ans[p:]) + sum(ans[p:p+e])))
else:
    print((sum(ans)))


# Optimized solution
n, x, m = list(map(int, input().split()))

ans = []
c = [0]*m
flag = False
for i in range(n):
    if c[x] == 1:
        flag = True
        break
    ans.append(x)
    c[x] = 1
    x = x**2 % m
if flag:
    p = ans.index(x)
    l = len(ans) - p
    d, e = divmod(n-p, l)
    print((sum(ans[:p]) + d*sum(ans[p:]) + sum(ans[p:p+e])))
else:
    print((sum(ans)))
# Original solution
n, x, m = list(map(int, input().split()))
l = [x]
loop = []
a = x

for i in range(n - 1):
    a = a**2%m
    if a not in l:
        l.append(a)
    else:
        if a not in loop:
            loop.append(a)
        else:
            break

if len(loop) > 0:
    rest = (n - len(l))%len(loop)
    times = (n - len(l))//len(loop)
    ans = sum(l) + sum(loop)*times
    for i in range(rest):
        ans += loop[i]
else:
    ans = sum(l)

print(ans)

# Optimized solution
n, x, m = list(map(int, input().split()))
l = [x]
a = x
loopsum = 0
loopnum = 0


for i in range(n - 1):
    a = a**2%m
    if a not in l:
        l.append(a)
    else:
        pos = l.index(a)
        loopnum = len(l[pos:])
        loopsum = sum(l[pos:])
        break

if loopnum > 0:
    rest = (n - len(l))%loopnum
    times = (n - len(l))//loopnum
    ans = sum(l) + loopsum*times
    for i in range(rest):
        ans += l[pos + i]
else:
    ans = sum(l)

print(ans)
# Original solution
n, x, m = list(map(int, input().split()))
a = x
S = [0] * (m + 1)
F = [None] * m
F[x] = 0
i0, j0 = None, None
for i in range(1, m + 1):
    S[i] = S[i - 1] + a
    a = pow(a, 2, m)
    if F[a] is not None:
        i0, j0 = F[a], i
    F[a] = i
q, r = (n - i0) // (j0 - i0), (n - i0) % (j0 - i0)
print(((S[j0] - S[i0]) * q + S[i0 + r]))


# Optimized solution
n, x, m = list(map(int, input().split()))
S = [0]
F = [None] * m
for i in range(m + 1):
    S.append(S[-1] + x)
    if F[x] is not None:
        j = F[x]
        q, r = (n - j) // (i - j), (n - j) % (i - j)
        print(((S[i] - S[j]) * q + S[j + r]))
        exit()
    F[x] = i
    x = pow(x, 2, m)
print((0))
# Original solution
n, x, m = list(map(int, input().split()))
S = [0]
F = [None] * m
for i in range(m + 1):
    S.append(S[-1] + x)
    if F[x] is not None:
        j = F[x]
        q, r = (n - j) // (i - j), (n - j) % (i - j)
        print(((S[i] - S[j]) * q + S[j + r]))
        exit()
    F[x] = i
    x = pow(x, 2, m)
print((0))


# Optimized solution
n, x, m = list(map(int, input().split()))
S = [0]
F = [None] * m
for i in range(m + 1):
    S.append(S[-1] + x)
    if F[x] is not None:
        j = F[x]
        q, r = (n - j) // (i - j), (n - j) % (i - j)
        print(((S[i] - S[j]) * q + S[j + r]))
        exit()
    F[x] = i
    x = pow(x, 2, m)
# Original solution
from collections import deque

N, K = list(map(int, input().split()))
T = [[] for i in range(N)]
E = []
for i in range(N-1):
    a, b = list(map(int, input().split()))
    a, b = a-1, b-1
    T[a].append(b)
    T[b].append(a)
    E.append((a, b))


def dfs(n):
    visited = [False] * N
    stack = [[n, 0]]
    longest = [-1, -1]

    while stack:
        node, weight = stack.pop()
        if visited[node]:
            continue
        visited[node] = True
        if longest[1] < weight:
            longest = [node, weight]

        for n in T[node]:
            if not visited[n]:
                stack.append([n, weight + 1])

    return longest


def bfs(n):
    visited = [False] * N
    dist = [0] * N
    queue = deque([n])
    while queue:
        node = queue.pop()
        if visited[node]:
            continue
        visited[node] = True
        for n in T[node]:
            if not visited[n]:
                dist[n] = dist[node] + 1
                queue.appendleft(n)
    return dist


xn, xw = dfs(0)
yn, yw = dfs(xn)
diameter = yw

d = bfs(0)
ans = float('inf')
if K % 2 == 0:
    # 全ての頂点について全探索
    for i in range(N):
        dist = bfs(i)
        ans = min(ans, len(list([x for x in dist if K / 2 < x])))
else:
    # 全ての辺について全探索
    for a, b in E:
        dist1 = bfs(a)
        dist2 = bfs(b)
        dist = [min(d1, d2) for d1, d2 in zip(dist1, dist2)]
        ans = min(ans, len(list([x for x in dist if (K-1) / 2 < x])))

print(ans)


# Optimized solution
from collections import deque

N, K = list(map(int, input().split()))
T = [[] for i in range(N)]
E = []
for i in range(N-1):
    a, b = list(map(int, input().split()))
    a, b = a-1, b-1
    T[a].append(b)
    T[b].append(a)
    E.append((a, b))


def bfs(n):
    visited = [False] * N
    dist = [0] * N
    queue = deque([n])
    while queue:
        node = queue.pop()
        if visited[node]:
            continue
        visited[node] = True
        for n in T[node]:
            if not visited[n]:
                dist[n] = dist[node] + 1
                queue.appendleft(n)
    return dist


dist = []
for i in range(N):
    dist.append(bfs(i))

ans = float('inf')
if K % 2 == 0:
    # 全ての頂点について全探索
    for i in range(N):
        ans = min(ans, len(list([x for x in dist[i] if K / 2 < x])))
else:
    # 全ての辺について全探索
    for a, b in E:
        adist = [min(d1, d2) for d1, d2 in zip(dist[a], dist[b])]
        ans = min(ans, len(list([x for x in adist if (K-1) / 2 < x])))

print(ans)
# Original solution
from collections import deque

N, K = list(map(int, input().split()))
T = [[] for i in range(N)]
E = []
for i in range(N-1):
    a, b = list(map(int, input().split()))
    a, b = a-1, b-1
    T[a].append(b)
    T[b].append(a)
    E.append((a, b))


def bfs(n):
    visited = [False] * N
    dist = [0] * N
    queue = deque([n])
    while queue:
        node = queue.pop()
        if visited[node]:
            continue
        visited[node] = True
        for n in T[node]:
            if not visited[n]:
                dist[n] = dist[node] + 1
                queue.appendleft(n)
    return dist


dist = []
for i in range(N):
    dist.append(bfs(i))

ans = float('inf')
if K % 2 == 0:
    # 全ての頂点について全探索
    for i in range(N):
        ans = min(ans, len([d for d in dist[i] if d > K / 2]))
else:
    # 全ての辺について全探索
    for a, b in E:
        adist = [(1 if min(d1, d2) > (K-1) / 2 else 0) for d1, d2 in zip(dist[a], dist[b])]
        ans = min(ans, sum(adist))

print(ans)


# Optimized solution
from collections import deque

N, K = list(map(int, input().split()))
T = [[] for i in range(N)]
E = []
for i in range(N-1):
    a, b = list(map(int, input().split()))
    a, b = a-1, b-1
    T[a].append(b)
    T[b].append(a)
    E.append([a, b])


def bfs(n):
    visited = [False] * N
    dist = [0] * N
    queue = deque([n])
    while queue:
        node = queue.pop()
        if visited[node]:
            continue
        visited[node] = True
        for n in T[node]:
            if not visited[n]:
                dist[n] = dist[node] + 1
                queue.appendleft(n)
    return dist


dist = []
for i in range(N):
    dist.append(bfs(i))

ans = float('inf')
if K % 2 == 0:
    for i in range(N):
        ans = min(ans, len([d for d in dist[i] if d > K / 2]))
else:
    for a, b in E:
        ans = min(ans, len([d for d in [min(d1, d2) for d1, d2 in zip(dist[a], dist[b])] if d > (K-1) / 2]))

print(ans)