#include <bits/stdc++.h>
using namespace std;
long long N, X, M;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cin >> N >> X >> M;
  long long curr = X;
  vector<long long> path;
  path.push_back(curr);
  set<long long> vis;
  vis.insert(curr);
  long long hf, result = curr, req = N - 1;
  for (int i = 2; i <= N; i++) {
    curr = (curr * curr) % M;
    if (vis.find(curr) != vis.end()) {
      hf = curr;
      break;
    }
    result += curr;
    req -= 1;
    path.push_back(curr);
    vis.insert(curr);
  }
  long long ix = find(path.begin(), path.end(), hf) - path.begin();
  long long sz = path.size() - ix;
  long long score = accumulate(path.begin() + ix, path.end(), 0ll);
  if (req) {
    result += score * (req / sz);
    long long rem = (req % sz), iy = ix;
    while (rem--) {
      result += path[iy];
      iy += 1;
    }
  }
  cout << result << "\n";
}
