C++ 程序执行费马素数测试
c++server side programmingprogramming
费马素数测试用于检查给定数字是否为素数。以下是此算法的 C++ 代码。
算法
Begin modulo(base, e, mod) a = 1 b = base while (e > 0) if (e mod 2 == 1) a = (a * b) % mod b = (b * b) % mod e = e / 2 return a % mod End Begin Fermat(ll m, int iterations) if (m == 1) return false done for (int i = 0; i < iterations; i++) ll x = rand() mod (m - 1) + 1 if (modulo(x, m - 1, m) != 1) return false done return true End
示例代码
#include <cstring> #include <iostream> #include <cstdlib> #define ll long long using namespace std; ll modulo(ll base, ll e, ll mod) { ll a = 1; ll b = base; while (e > 0) { if (e % 2 == 1) a = (a * b) % mod; b = (b * b) % mod; e = e / 2; } return a % mod; } bool Fermat(ll m, int iterations) { if (m == 1) { return false; } for (int i = 0; i < iterations; i++) { ll x = rand() % (m - 1) + 1; if (modulo(x, m - 1, m) != 1) { return false; } } return true; } int main() { int iteration = 70; ll num; cout<<"输入整数以测试素数:"; cin>>num; if (Fermat(num, iteration)) cout<<num<<" 为素数"<<endl; else cout<<num<<" 不是素数"<<endl; return 0; }
输出
输入整数以测试素数:13 为素数