program main
    use,intrinsic :: iso_fortran_env
    implicit none
    integer(int64):: n,x,m
    integer(int64):: i,ndata,lloop,nloop,nlast
    integer(int64):: ans=0,loop_s=0
    integer(int64), allocatable:: ind(:),v(:)

    read*, n,x,m
    allocate(ind(0:m),source=0_8)
    allocate(v(0:m))
    v(1)=x
    ind(x)=1
    
    do i=2_8,m
        v(i)=next_v(i-1)
        if (ind(v(i)) /= 0) then
            ndata = i-1
            lloop=i-ind(v(i))
            exit
        end if
        ind(v(i)) = i
    end do

    if (n <= ndata) then
        do i=1,n
            ans=ans+v(i)
        end do
    else
        do i=1,ndata
            ans=ans+v(i)
        end do

        do i=ind(next_v(ndata)),ind(v(ndata))
            loop_s=loop_s+v(i)
        end do

        nloop = (n-ndata)/lloop
        ans=ans+nloop*loop_s
        nlast = n - ndata - nloop*lloop
        do i=ind(next_v(ndata)),ind(next_v(ndata))+nlast-1
            ans=ans+v(i)
        end do
    end if
    print'(i0)', ans
contains
    function next_v(i) result(ret)
        integer(int64):: i,ret
        ret = mod(v(i)*v(i),m)
    end function

end program main