// 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;
}