#include <bits/stdc++.h>
using namespace std;
int main() {
  long long n, x, m;
  cin >> n >> x >> m;
  long long k;
  k = 0;
  long long A[n];
  A[0] = x;
  A[1] = (x * x) % m;
  int q;
  q = 0;
  int l;
  while (q == 0) {
    for (int i = 1; i < n - 1; i++) {
      for (int l = 0; l < i; l++) {
        if (A[i] == A[l]) {
          q = 1;
          for (int p = i; p < n - 1; p++) {
            A[p + 1] = A[p - i + l + 1];
          }
        } else
          A[i + 1] = (A[i] * A[i]) % m;
      }
      if (i == n - 2) {
        q = 1;
      }
    }
  }
  for (int j = 0; j < n; j++) {
    k += A[j];
  }
  cout << k << endl;
  return 0;
}
