#include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007LL;
long long check[110000];
int main() {
  long long n, x, m;
  cin >> n >> x >> m;
  vector<long long> v;
  long long cnt = 0LL;
  long long a = x;
  for (int i = 0; i < n; i++) {
    v.push_back(a);
    cnt += a;
    check[a] = true;
    a *= a;
    a %= m;
    if (check[a]) break;
    if (a == 0) {
      cout << cnt << endl;
      return 0;
    }
  }
  long long ans = 0LL;
  bool swi = true;
  vector<long long> vv;
  long long vs = v.size();
  for (int i = 0; i < vs; i++) {
    if (v[i] == a) swi = false;
    if (swi) {
      ans += v[i];
      n--;
    } else
      vv.push_back(v[i]);
  }
  long long s = vv.size();
  if (s == 0) {
    long long sum = 0LL;
    n += vs;
    for (int i = 0; i < vs; i++) sum += v[i];
    ans += sum * (n / vs);
    for (int i = 0; i < n % vs; i++) ans += v[i];
    cout << ans << endl;
    return 0;
  }
  long long sum = 0LL;
  for (int i = 0; i < s; i++) sum += vv[i];
  ans += sum * (n / s);
  for (int i = 0; i < n % s; i++) ans += vv[i];
  cout << ans << endl;
  return 0;
}
