码迷,mamicode.com
首页 > 其他好文 > 详细

数论 - 最小乘法逆元

时间:2016-08-10 19:06:54      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

我只能说这个数论定理对我一脸懵比,哦不对,是我对这个数论定理一脸懵比,暂时

只准备记住模板就好了,求最小逆元的时候可以用一下,如果mod为素数而且不要求

最小的话还是用费马小定理吧,对了还是要说一下,这个模板中exgcd(扩展欧几里德)

的返回值是gcd(最大公约数),其中x才是要求的逆元,而且一求出来时并不是最小

而且还有可能是负数,有点分类讨论了,不过我找模板的时候把分类讨论那里用一个更

优的方案代替了(也是找的),用的时候注意点,不说了,我还是准备懵比去吧= =

 

 

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<vector>
#include<queue>
#include<cctype>
using namespace std;

#define Int __int64
#define INF 0x3f3f3f3f

int exgcd(int a, int b, int &x, int &y) {
  if (b == 0) {
    x = 1;
    y = 0;
    return a;
  }
  int gcd = exgcd(b, a%b, x, y);
  int t = y;
  y = x - a/b*y;
  x = t;
  return gcd;
}
int main()
{
  //freopen("input.txt", "r", stdin);
  int n, m, x, y;
  while (scanf("%d%d", &n, &m) != EOF) {
    int gcd = exgcd(n, m, x, y);
    int q = m / gcd;
    x = ((x % q) + q)%q;
    printf("%d\n", x);
  }
  return 0;
}

数论 - 最小乘法逆元

标签:

原文地址:http://www.cnblogs.com/steamedbun/p/5757769.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!