//模指数运算函数
#include<iostream>
using namespace std;
#include<math.h>
int Mod_Exp(int a, int b, int m)
{
int result = 1;
while (b > 0)
{
if ((b & 1) == 1)
{
result = (result * a) % m;
}
b >>= 1;
a = a * a % m;
}
return result;
}
//2.乘法逆元(此处有两种解法,需要注意如果两个数不互质应该是没有乘法逆元的)
//一.遍历
#include<iostream>
using namespace std;
int gcd(int a, int b)//gcd算法
{
int t;
while (b > 0) {
t = a % b;
a = b;
b = t;
}
return a;
}
int Mul_inverse(int a, int m)
{
if (gcd(a, m) == 1)
{
int c;
for (int i = 1;; i++)
{
if (i * a % m == 1)
{
c = i;
break;
}
}
return c;
}
else
return 0;
}
int main()
{
int p= Mul_inverse(3, 11);
if (p != 0)
cout << "乘法逆元为:" << p;
else
cout << "这两数不互质,无乘法逆元";
}
//二.egcd算法求乘法逆元
#include<iostream>
using namespace std;
int gcd(int a, int b)//gcd算法
{
int t;
while (b > 0) {
t = a % b;
a = b;
b = t;
}
return a;
}
int* egcd(int a, int b)
{
int* arr = new int[3];
int temp;
int r1 = 1, s1 = 0;
int r2 = 0, s2 = 1;
int r3, s3;
int xishu;
while (b != 0)
{
xishu = a / b;
temp = a % b;
a = b;
b = temp;
r3 = r1 - xishu * r2;
s3 = s1 - xishu * s2;
r1 = r2;
s1 = s2;
s2 = s3;
r2 = r3;
}
arr[0] = r1;
arr[1] = s1;
arr[2] = a;
return arr;
}
int Mul_inverse1
CINTA作业三
最新推荐文章于 2024-08-22 17:27:46 发布