zoukankan      html  css  js  c++  java
  • Modular Inverse (拓展欧几里得求逆元)

    The modular modular multiplicative inverse of an integer a modulo m is an integer xsuch 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

    今晚实在是想吐槽一下这个题,很无奈啊,本来想四题签到跑路,被这个题卡了2个小时,首先暴力枚举得没过,然后翻板子在拓展欧几里的找到了类似得题目,把板子搞上,疯狂wa,wa到自闭,结果是一组m为1时的特例为1,程序输出为0,还是太菜了,真************(疯狂喷自己)

    代码:

    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<iostream>
    #include<queue>
    #include<stack>
    #include<set>
    #include<vector>
    #include<map>
    #include<cmath>
    const int maxn=1e5+5;
    typedef long long ll;
    using namespace std;
    int  extend_gcd(int a,int b,int &x,int &y)
    {
    	if(a==0&&b==0)
    	{
    		return -1;
    	}
    	if(b==0)
    	{
    		x=1;y=0;
    		return a;
    	}
    	int  d=extend_gcd(b,a%b,y,x);
    	y-=a/b*x;
    	return d;
    }
    int mod_reverse(int a,int  n)
    {
    	int x,y;
    	int d=extend_gcd(a,n,x,y);
    	if(d==1)return(x%n+n)%n;
    	else return -1;
    }
    int main()
    {
    	int T;
    	cin>>T;
    	while(T--)
    	{
    		int  a,n;
    		cin>>a>>n;
    		if(n==1)
    		{
    			cout<<1<<endl;
    			continue;
    		}
    		if(__gcd(a,n)!=1)
    		{
    			cout<<"Not Exist"<<endl;
    			continue;
    		}
    		cout<<mod_reverse(a,n)<<endl;
    	}
    	
    	return 0;
    }
  • 相关阅读:
    JOISC2020 题解
    Linux系统时钟与硬件时钟
    Excel Application操作指南
    WinCC 7.5 SP1安装方法
    关于WinCC V15.1使用ActiveX的ListView控件时添加失败问题
    WinCC 利用VBScript连接mysql数据库
    WPF中通过AForge实现USB摄像头拍照
    ESP32引脚参考
    C语言创建循环缓冲区(环形缓冲区)-- Circular Buffer(Ring Buffer)
    Android Studio汉化教程
  • 原文地址:https://www.cnblogs.com/Staceyacm/p/10781782.html
Copyright © 2011-2022 走看看