由 费马小定理可知:
a ^ b % m = a ^ ( b % (m-1) ) % m ;
(费马小定理:m是质数时 a ^ (m-1) % m = 1)
所以对于本题 枚举 a 的 1 - p 次幂对 p 取模,
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
#include <set>
#include <stack>
#include <map>
#include <climits>
using namespace std;
typedef long long ll;
const int maxn = 10 + 7, INF = 0x3f3f3f3f, mod = 1e9 + 7;
ll p, a, b, x;
bool solve(ll n) {
//cout << n << " ";
ll ans = 1;
ll t = a;
while(n) {
if(n & 1) ans *= t, ans %= p;
t = t * t; t %= p;
n /= 2;
}
//cout << ans << " == " << endl;
if(ans == b) return true;
else return false;
}
int main() {
ios::sync_with_stdio(0);
cin >> p;
while(cin >> a && a) {
cin >> b;
int f = 0;
for(ll i = 1; i < p; ++i) {
if(solve(i)) { cout << i << endl; f = 1; break;}
}
if(!f) cout << 0 << endl;
}
return 0;
}