C++ 程序实现费马小定理
费马小定理是初等数论的一个基本结果,是费马素数检验的基础。该定理以皮埃尔·德·费马命名,他于 1640 年提出了该定理。该定理指出,如果 p 是素数,则对于任何整数 a,数 ap–a 是 p 的整数倍。
算法
Begin Function power() is used to compute a raised to power b under modulo M function modInverse() to find modular inverse of a under modulo m : Let m is prime If a and m are relatively prime, then modulo inverse is a^(m - 2) mod m End
示例代码
#include <iostream>
using namespace std;
int pow(int a, int b, int M) {
int x = 1, y = a;
while (b > 0) {
if (b % 2 == 1) {
x = (x * y);
if (x > M)
x %= M;
}
y = (y * y);
if (y > M)
y %= M;
b /= 2;
}
return x;
}
int modInverse(int a, int m) {
return pow(a, m - 2, m);
}
int main() {
int a, m;
cout<<"Enter number to find modular multiplicative inverse: ";
cin>>a;
cout<<"Enter Modular Value: ";
cin>>m;
cout<<modInverse(a, m)<<endl;
}输出
Enter number to find modular multiplicative inverse: 26 Enter Modular Value: 7 3
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP