您的位置:首页 > 其它

ZOJ 3609 Modular Inverse (水题)

2014-08-21 10:32 441 查看

Modular Inverse

Time Limit: 2 Seconds Memory Limit: 65536 KB
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

http://en.wikipedia.org/wiki/Modular_inverse

Author: WU, Zejun
Contest: The 9th Zhejiang Provincial Collegiate Programming Contest

简单来说就是要求给定n,m 求一个x使得 (n*x)%m=1, 如果x存在输出最小正整数x,否则输出Not Exist

注意m=1的情况,因为任何数对1取模会等于0,但是这里要求输出最小正整数,所以输出1

#include<cstdio>
#include<cstring>
#include<stdlib.h>
#include<algorithm>
using namespace std;
int gcd(int a,int b)
{
return b?gcd(b,a%b):a;
}
int main()
{
//freopen("in.txt","r",stdin);
int kase;
scanf("%d",&kase);
while(kase--)
{
int n,m;
scanf("%d %d",&n,&m);

if(m==1)//当m=1时,数字对1取模等于0,存在这个数字,但是这里要输出最小的正整数,所以输出1
{printf("1\n");continue;}

int Gcd=gcd(n,m);

if(Gcd>1)
{printf("Not Exist\n");continue;}

else
for(int i=1;i<=1000;i++)
if((n*i)%m==1)
{printf("%d\n",i);break;}
}
return 0;
}


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