#include <bits/stdc++.h>
using namespace std;
const int INF = 1000000007;
const long long MOD = 1000000007;
void solve_test() {
  long long n, x, m;
  cin >> n >> x >> m;
  long long pos[m + 1];
  for (int i = 0; i <= m; i++) {
    pos[i] = -1;
  }
  long long val = x;
  long long ans = 0;
  long long period = 1;
  long long sum[m + 1];
  long long st = n;
  memset(sum, 0, sizeof(sum));
  long long diff = 0;
  for (long long i = 0; i < min(n, m); i++) {
    if (pos[val] != -1) {
      period = i - pos[val];
      st = pos[val];
      diff = sum[i - 1];
      if (st > 0) {
        diff -= sum[st - 1];
      }
      break;
    }
    sum[i] += val;
    pos[val] = i;
    val = (val * val) % m;
    if (i) {
      sum[i] += sum[i - 1];
    }
  }
  if (st - 1 <= m) {
    ans += sum[st - 1];
  }
  if (st != n) {
    long long q = (n - st) / period;
    long long r = (n - st) % period;
    cerr << "ans"
         << " is " << ans << endl;
    ;
    ans += q * diff;
    for (long long i = 0; i < r; i++) {
      ans += val;
      val = (val * val) % m;
    }
  }
  cout << ans;
}
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int tests;
  tests = 1;
  while (tests--) {
    solve_test();
  }
  return 0;
}
