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

ans = X
A = X
TF = True
srt = 1000000
retu = dict()
retu[X] = 1
loop = X
for i in range(N-1):
    if TF:
        A = A**2 % M
        if retu.get(A) != None:
          srt = j
          goal = i
          TF = False
          break   
        if TF:
          retu[A] = 1
          loop += A
    else:
      break
      
if N-1 > srt:
    n = (N-srt)//(goal-srt+1)
    saisyo = sum(retu[:srt])
    loop -= saisyo
    print(saisyo + loop*n + sum(retu[srt:N-n*(goal-srt+1)]))
    
else:
    print(sum(retu[:N]))
