您的位置:首页 > 其它

求逆元两种方法 hdu-1576-A/B

2013-06-11 18:14 274 查看
题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=1576

题目意思:

求出A/B mod 9973的值,n=A mod 9973 ,gcd(B,9973)=1.

因为gcd(B,9973)=1.

可以用费马小定理和扩展欧几里得算法两种方法来求B的逆元,然后化除法为乘法。

代码:

#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#include<map>
#include<stack>
#include<list>
#include<queue>
#define eps 1e-6
#define INF (1<<30)
#define PI acos(-1.0)
using namespace std;

#define ll __int64

ll quick(ll a,ll b,ll m) //用费马小定理解
{
   ll res=1;

   while(b)
   {
      if(b&1)
         res=(res*a)%m;
      a=(a*a)%m;
      b=b>>1;
   }
   return res;
}

void egcd(int a,int b,int &x,int &y) //用扩展的欧几里得算法解
{
   if(b==0)
   {
      x=1;y=0;
      return ;
   }
   egcd(b,a%b,x,y);
   int temp=x;
   x=y,y=temp-a/b*y;
   return ;
}

int main()
{
   int t;
   int n,b;

   scanf("%d",&t);
   while(t--)
   {
      scanf("%d%d",&n,&b);
      int x,y;

     /* egcd(b,9973,x,y);
      x=x%9973;
      if(x<0)
         x+=9973;

      printf("%d\n",(n*x)%9973);*/

      printf("%d\n",(n*quick(b,9973-2,9973))%9973);
   }

   return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: