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>
相关文章推荐
- 【Jason's_ACM_解题报告】Calculator Conundrum
- USTCOJ1381 老式计算器 uva11549 (Set判重、Floyd判圈)
- uva11549 Calculator Conundrum【解法二】
- LeetCode-202-Happy Number-E
- PopupWindow
- 关于 iOS delegate 的遐想
- POJ2002&&POJ3432 Squares(二分||hash)
- Mybatis中的resultType和resultMap
- 在AndroidStudio中使用Eclipse下的CodeFormates和CodeTemplates
- Win2003和Win2008防火墙导致FTP服务器不能访问的解决方法(转载自http://www.jb51.net/article/57008.htm)
- 编码技巧集锦
- 前端面试题
- hadoop学习笔记
- JAVA基础知识备忘
- Android SO逆向-对象的继承和虚函数
- PHP 安全
- sqoop1.4.6+hadoop2.6.2安装
- 源代码jar包中的中文注释乱码
- 逻辑地址、线性地址、物理地址和虚拟地址理解
- 开源图片加载框架——Universal-Image-Loader学习