用费马小定理求逆元和扩展欧几里得求逆元

用例题来讲
hud1576

A/B
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 12100 Accepted Submission(s): 9712

Problem Description
要求(A/B)%9973,但由于A很大,我们只给出n(n=A%9973)(我们给定的A必能被B整除,且gcd(B,9973) = 1)。

Input
数据的第一行是一个T,表示有T组数据。
每组数据有两个数n(0 <= n < 9973)和B(1 <= B <= 10^9)。

Output
对应每组数据输出(A/B)%9973。

Sample Input
2
1000 53
87 123456789

Sample Output
7922
6060

如果用欧几里得来求逆元的代码如下
因为 ax+py=1;
用扩展欧几里得定理求出来的x即为a的逆元。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 1e5+5;
typedef long long ll;
ll q=0;
ll exgcd(ll a,ll b,ll &x,ll &y)
{
    if(b==0){
        x=1;y=0;
        return a;
    }
    ll ans=exgcd(b,a%b,x,y);
    ll t=x;
    x=y;
    y=t-(a/b)*y;
    return ans;
}
int main()
{
    ll b;
    ll n;
    ll t;
    cin>>t;
    while(t--){
        cin>>n>>b;
        ll x,y;
        ll s=exgcd(b,9973,x,y);
        if(x<0)x+=9973;
        cout<<(n*(x%9973)+9973)%9973<<endl;
    }
    return 0;
}

而使用费马小定理的代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 1e5+5;
const int mod =9973;
typedef long long ll;
ll q=0;
ll qpow(ll a,ll b)
{
    ll ans=1;
    while(b){
        if(b&1){
            ans=ans*a%mod;
        }
        b>>=1;
        a=a*a%mod;
    }
    return ans%mod;
}
int main()
{
    ll b;
    ll n;
    ll t;
    cin>>t;
    while(t--){
        cin>>n>>b;
        ll s=qpow(b,9971);
        cout<<(n*s)%mod<<endl;
    }
    return 0;
}

发布了35 篇原创文章 · 获赞 25 · 访问量 831

猜你喜欢

转载自blog.csdn.net/qq_43816599/article/details/98176336