#include <iostream>
#include <sstream>
#include <iomanip>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <numeric>
#include <iterator>
#include <functional>
#include <complex>
#include <queue>
#include <stack>
#include <cmath>
#include <cassert>
#include <cstring>
using namespace std;
typedef long long LL;
typedef complex<double> CMP;

class BunnyConverter { public:
	vector< vector<int> > n_sqrt;

	int getMinimum(int n, int z, int start, int goal) 
	{
		n_sqrt.resize(n);
		for(LL y=0; y<n; ++y)
			n_sqrt[y*y%n].push_back(int(y?y:n));

		set<int> v;
		v.insert(start);
		vector<int> q(1,start);
		for(int step=0; !q.empty(); ++step)
		{
			vector<int> qNext;
			for(int i=0; i<q.size(); ++i)
			{
				int x = q[i];
				if( x == goal )
					return step;
				const vector<int>& ys = next(x,z,n);
				for(int j=0; j<ys.size(); ++j)
				{
					int y = ys[j];
					if( v.insert(y).second )
						qNext.push_back(y);
				}
			}
			q.swap(qNext);
		}
		return -1;
	}


	const vector<int>& next(LL x, LL z, LL n)
	{
		x %= n;
		z %= n;
		#define SUB(a,b) (((a)+n-(b))%n)
		#define MUL(a,b) ((a)*(b)%n)
		LL y2 = SUB(SUB(0, x), MUL(z,MUL(z,z)));
		return n_sqrt[int(y2)];
	}
};

// BEGIN CUT HERE
#include <ctime>
double start_time; string timer()
 { ostringstream os; os << " (" << int((clock()-start_time)/CLOCKS_PER_SEC*1000) << " msec)"; return os.str(); }
template<typename T> ostream& operator<<(ostream& os, const vector<T>& v)
 { os << "{ ";
   for(typename vector<T>::const_iterator it=v.begin(); it!=v.end(); ++it)
   os << '\"' << *it << '\"' << (it+1==v.end() ? "" : ", "); os << " }"; return os; }
void verify_case(const int& Expected, const int& Received) {
 bool ok = (Expected == Received);
 if(ok) cerr << "PASSED" << timer() << endl;  else { cerr << "FAILED" << timer() << endl;
 cerr << "\to: \"" << Expected << '\"' << endl << "\tx: \"" << Received << '\"' << endl; } }
#define CASE(N) {cerr << "Test Case #" << N << "..." << flush; start_time=clock();
#define END	 verify_case(_, BunnyConverter().getMinimum(n, z, start, goal));}
int main(){

CASE(0)
	int n = 5; 
	int z = 1; 
	int start = 5; 
	int goal = 3; 
	int _ = 1; 
END
CASE(1)
	int n = 5; 
	int z = 1; 
	int start = 5; 
	int goal = 1; 
	int _ = 2; 
END
CASE(2)
	int n = 6; 
	int z = 2; 
	int start = 3; 
	int goal = 4; 
	int _ = -1; 
END
CASE(3)
	int n = 7; 
	int z = 7; 
	int start = 7; 
	int goal = 7; 
	int _ = 0; 
END
CASE(4)
	int n = 499979; 
	int z = 499979; 
	int start = 499976; 
	int goal = 3; 
	int _ = 249988; 
END
/*
CASE(5)
	int n = ; 
	int z = ; 
	int start = ; 
	int goal = ; 
	int _ = ; 
END
CASE(6)
	int n = ; 
	int z = ; 
	int start = ; 
	int goal = ; 
	int _ = ; 
END
*/
}
// END CUT HERE
