首先乘法逆的意思其实就是说如下:
算法如下所示:
上图伪代码不是很清晰,我稍微修改一下:
//首先进行赋值
r1 =n; r2 = b;
t1 = 0; t2 = 1;
if(r2>0)
{
//对r的值进行修改(其实相当于求最大公约数的循环)
q = r1/r2;
r = r1 - q * r2;
r1 = r2;
r2 = r;
//修改t值
t = t1 - q * t2;
t1 = t2;
t2 = t;
}
示例如下:
#include <iostream>
#include <set>
using namespace std;
int ans[100] = {0};
int com(int r1, int r2){ // 求出r2对于r1有没有乘法逆,若有,其实就是求出的结果和r2互为乘法逆
int q, r, t1 = 0, t2 = 1, t;
bool k = true;
int n = r1;
while(k){
if(r2 > 0){
q = r1 / r2;
r = r1 - q * r2;
r1 = r2;
r2 = r;
t = t1 - q * t2;
t1 = t2;
t2 = t;
if(r1 == 1){
k = false;
return t1 < 0 ? (n+t1):(n-t1);
}
}else{
k = false;
}
}
return 0;
}
/*
测试数据
输入26,如下为结果
1
3
5
7
9
11
15
17
19
21
23
25
*/
int main(){
set<int> s;
int r1;
cin >> r1;
for(int i = 1 ; i < r1; i++){
int temp = com(r1,i);
if(temp!=0){
ans[i] = 1;
ans[temp] = 1;
}
}
for(int i = 0 ; i < 100 ; i++){
if(ans[i] == 1){
cout << i <<endl;
}
}
return 0;
}