数论 逆元

纯逆元题目如下,便于理解:

A/B

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7541    Accepted Submission(s): 5996


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
 

思路:逆元,对于求解(a/b)%m的式子中,有的时候我们会发现在计算过程中会有非常大的a,以至于超出了long long 的范围导致无法储存,所以我们只能先输入a%m;现在给出了整数n,b;分别代表a%m以及整数b,求解(a/b)%m;

对于(a/b)%m我们可以利用拓展欧几里得求出b关于m的逆元,通过公式

(a/b)%m=(a%m*inv(b))%m求解

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
const int MAX_N=11000000;
#define inf 1<<23
typedef long long ll;
typedef long long LL;
#define m 9973
void exgcd(int a,int b,int &x,int &y)
{
    if(b==0)
    {
        x=1,y=0;
        return ;
    }
    exgcd(b,a%b,x,y);
    int r=x;
    x=y;
    y=r-(a/b)*y;
}
int main()
{
    int t;
    int x,y;
    int n,b;
    while(scanf("%d",&t)!=EOF)
    {
        while(t--)
        {
            scanf("%d%d",&n,&b);
            
            //m=9973
            exgcd(b,m,x,y);
            
            //这样求出的逆元x可能为负值,通过下面的公式进行转化
            x=(x%m+m)%m;
            
            printf("%d\n",(x*n)%m);
            //输出分解 n=a%m;
            //原式等于(x*(a%m))%m=(x%m*(a%m)%m)%m;
            //即(a/b)%m=inv(b)%m*a%m;
        }
    }

    return 0;
}


你可能感兴趣的:(芝士就是力量)