ZOJ-3609(Modular Inverse )(拓展欧几里得)
2017-04-16 22:49
399 查看
The modular modular multiplicative inverse of an integer a modulo m is an integer x such that a-1≡x (mod m). This is equivalent to ax≡1 (mod m).
Input
There are multiple test cases. The first line of input is an integer T ≈ 2000 indicating the number of test cases.
Each test case contains two integers 0 < a ≤ 1000 and 0 < m ≤ 1000.
Output
For each test case, output the smallest positive x. If such x doesn’t exist, output “Not Exist”.
Sample Input
3
3 11
4 12
5 13
Sample Output
4
Not Exist
8
References
题意,求一个最小的正数使得ax %m == 1
我们可以将这个式子展开即(ax-1) % m = 0 ,即ax-1 = y*m,将其移动到右边即是ax - my = 1,显然我们要用到扩展欧几里得,详细解释在代码注释里面
代码如下:
Input
There are multiple test cases. The first line of input is an integer T ≈ 2000 indicating the number of test cases.
Each test case contains two integers 0 < a ≤ 1000 and 0 < m ≤ 1000.
Output
For each test case, output the smallest positive x. If such x doesn’t exist, output “Not Exist”.
Sample Input
3
3 11
4 12
5 13
Sample Output
4
Not Exist
8
References
题意,求一个最小的正数使得ax %m == 1
我们可以将这个式子展开即(ax-1) % m = 0 ,即ax-1 = y*m,将其移动到右边即是ax - my = 1,显然我们要用到扩展欧几里得,详细解释在代码注释里面
代码如下:
#include<iostream> #include<algorithm> #include<cmath> using namespace std; int t,a,m; typedef long long ll; ll extgcd(ll a,ll b,ll &x,ll &y){//我表示没有看懂,展示当模板强行记住,我好笨啊。 ll d = a; if(b != 0){ d = extgcd(b,a%b,y,x); y -= (a/b)*x; }else{ x = 1; y = 0; } return d; } int main(void) { ll t; cin >> t; while(t--){ cin >> a >> m; ll x,y; ll ans = extgcd(a,m,x,y); if(ans != 1) cout << "Not Exist" << endl; else{ /*因为拓展欧几里得是求ax+by=1的解,这里是ax-by=1,但当求的y为负数时 也可默认为前着转化为了后者 例如,我们得到一组解x0,y0那么a(x0+b)+b(y0-a)与原式相等,当x为正时,则y一定为负.*/ while(x <= 0) x += m; cout << x << endl; } } return 0; }
相关文章推荐
- ZOJ - 3609 —— Modular Inverse 【乘法逆,扩展欧几里得】
- ZOJ 3609 Modular Inverse【exgcd】
- Modular Inverse ZOJ - 3609
- (扩展欧几里得)Modular Inverse--Zoj
- J - Modular Inverse ZOJ - 3609 ----逆元
- ZOJ-3609-Modular Inverse【同余定理】【9th浙江省赛】
- ZOJ 3609 Modular Inverse【同余问题】
- 浙江省省赛第一发(扩展欧几里得)J Modular Inverse
- zoj 3609 Modular Inverse 求最小逆元 裸的的扩展欧几里得
- ZOJ 3606 Modular Inverse【乘法逆元】
- ZOJ(Modular Inverse)——最小乘法逆元
- [zoj 3774]Power of Fibonacci 数论(二次剩余 拓展欧几里得 等比数列求和)
- zoj Modular Inverse
- [zoj 3774]Power of Fibonacci 数论(二次剩余 拓展欧几里得 等比数列求和)
- ZOJ 3609 Modular Inverse 扩展欧几里得
- ZOJ 3609 Modular Inverse(扩展欧几里得求逆元)
- hdu 1576(拓展欧几里得)
- HDU 2669 Romantic(拓展欧几里得)
- 求解最大公约数——欧几里得算法及其(解同余方程)拓展欧几里得
- 青蛙的约会 POJ - 1061 拓展欧几里得