// asdasdasda as dasd
#include <bits/stdc++.h>
using namespace std;
#define REP(a,b,c) for(int a=b;a<c;a++)
#define asd(x) cout<<__LINE__<<" :: "<<#x<< ": "<<x<<endl;
#define asdf(x, y) cout<<__LINE__<<" :: "<<#x<< ": "<<x<<" | "<<#y<< ": "<<y<<endl;
#define lb() cout << string(15, =) << endl
typedef pair<int,int> ii;
typedef long long LL;
long long A, B, mod;
long long next(long long a){
return (a*A + a%B)%mod;
}
void yolo(long long slow){
int cyclelen = 1, len = 0;
long long a = slow, b = slow;
while(next(a) != b){
a = next(a);
cyclelen++;
}
a = 1, b = 1, len = cyclelen;
while(len--) b = next(b);
while(a != b) a = next(a), b = next(b), cyclelen++;
cout << cyclelen << endl;
exit(0);
}
int main(){
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
cin >> A >> B >> mod;
long long slow = 1, fast = 1, iter = 2e7;
while(iter){
slow = next(slow);
fast = next(next(fast));
if(slow == fast) yolo(slow);
iter--;
}
cout << -1 << endl;
return 0;
}
Ly8gYXNkYXNkYXNkYSBhcyBkYXNkIAojaW5jbHVkZSA8Yml0cy9zdGRjKysuaD4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKI2RlZmluZSBSRVAoYSxiLGMpIGZvcihpbnQgYT1iO2E8YzthKyspCiNkZWZpbmUgYXNkKHgpICAgICAgICAgICAgICBjb3V0PDxfX0xJTkVfXzw8IiA6OiAiPDwjeDw8ICI6ICI8PHg8PGVuZGw7CiNkZWZpbmUgYXNkZih4LCB5KSAgICAgICAgICBjb3V0PDxfX0xJTkVfXzw8IiA6OiAiPDwjeDw8ICI6ICI8PHg8PCIgfCAiPDwjeTw8ICI6ICI8PHk8PGVuZGw7CiNkZWZpbmUgbGIoKSBjb3V0IDw8IHN0cmluZygxNSwgPSkgPDwgZW5kbAp0eXBlZGVmIHBhaXI8aW50LGludD4gaWk7CnR5cGVkZWYgbG9uZyBsb25nIExMOwoKbG9uZyBsb25nIEEsIEIsIG1vZDsKCmxvb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