费马小定理

 1 #include 
 2 #include 
 3 #include 
 4  
 5 using namespace std;
 6  
 7 #define ll long long
 8 
 9 // a / b mod p
10 //满足条件 b 和 p互质
11 // a / b mod p = a * b^(p - 2) mod p
12  
13 ll gcd(ll a, ll b){
14     return b == 0 ? a : gcd(b, a % b);
15 }
16  
17 ll ksm(long long a, long long b, long long mod){
18     ll ans = 1;
19     while(b){
20         if(b & 1) ans = ans * a % mod;
21         a = a * a % mod;
22         b >>= 1;
23     }
24      
25     return ans;
26 }
27  
28 void solve(){
29      
30     int n;
31     scanf("%d", &n);
32     while(n--){
33         long long p, y;
34         scanf("%lld%lld", &y, &p);
35         if(gcd(p, y) != 1) printf("-1\n");
36         else printf("%lld\n", ksm(y, p - 2, p));
37     }
38 }
39  
40 int main(){
41      
42     solve();
43      
44     return 0;
45 }

 

你可能感兴趣的:(费马小定理)