#include <bits/stdc++.h>
int main() {
  long long int n, a[3], ans = 0, temp;
  int m, plus_minus = 1;
  scanf("%lld%lld%d", &n, &a[0], &m);
  ans += a[0];
  for (long long int i = 1; i < n; i++) {
    a[1 + plus_minus] = (a[1 - plus_minus] * a[1 - plus_minus]) % m;
    ans += a[1 + plus_minus];
    if (a[1 + plus_minus] <= 1) {
      temp = i;
      break;
    }
    plus_minus *= -1;
  }
  if (a[1 + plus_minus] == 1) {
    ans += n - temp;
  }
  printf("%lld", ans);
  return 0;
}
