您的位置:首页 > 其它

ZOJ 3609 Modular Inverse (FLOYD判圈算法)

2016-04-22 14:20 411 查看
Modular InverseTime Limit: 2 Seconds      Memory Limit: 65536 KBThe 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
题意:给出一个a和m,要求找到一个整数x满足:[code]ax≡1 (mod m)。
[/code]
思路:将算式化简一下,得到x=(k*m+1)/a ,要求x是整数,即判断有没有存在k使得x为整数,如果不存在的话,怎么证明不存在,这里就用到了FLOY判圈算法。
[/code]
这个算法简单的讲,就是要判断一个链表是否有环,只需要设置两个指针在同一个起点,一个指针每次向前走一步,另一个每次向前走两步,如果成环的话,两个指针会再次相遇。
[/code]
这里就用到这个原理,刚开始将k值都设置成1,然后p的值是每次加一个m后取模,q的值是每次加两个m后取模,看个值能否再次相等且不为0,如果相等且不为0,则有循环,即不存在。
[/code]
[/code]
<strong><span style="font-size:24px;">#include<iostream>using namespace std;int main(){int cases,i,a,m,p,q;cin>>cases;while(cases--){cin>>a>>m;if(a==1)//特殊情况处理,a=1时,x为1即可{cout<<1<<endl;continue;}p=(m+1)%a;q=p;//p和q两个指针的起点设置成相同for(i=1;;i++){if(i!=1)//i不等于1时开始走{p=(p+m)%a;//p每次前进一步,即加一个mq=(q+2*m)%a;//q每次前进两步,即加两个m}if(p==0){cout<<(i*m+1)/a<<endl;break;}//如果找到一个一个数能够被a整除,就停下来输出if(p==q&&p!=0&&i!=1)//如果在起点之后两个指针对应的数相同,且不为0,说明已经走到原位,循环存在{cout<<"Not Exist"<<endl;break;}}}return 0;}</span></strong>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  FLOYD判圈算法