C++ 语言使用 Rabin-Miller 素性测试实现检查给定数字是否为素数


Rabin-Miller 素性测试用于检查给定的数字是否为素数。它类似于形式素性和 Solovay-Stressen 测试。这项测试最初是由俄罗斯数学家 M. M. Artjuhov 发现的。

算法

Begin
   ll mulmod(ll a, ll b, ll m)
   ll x = 0,y = a mod m
   while (b > 0)
      if (b mod 2 == 1)
         compute x = (x + y) mod m
         y = (y * 2) mod m
         b = b/ 2
   return x mod m.
End

Begin
   ll modulo(ll base, ll e, ll m)
   Initialize:
   ll x = 1
   ll y = base
   while (e > 0)
      if (e mod 2 == 1)
         x = (x * y) mod m
         y = (y * y) mod m
         e = e / 2;
   return x mod m
End

Begin
   bool Miller(ll p, int iteration)
   if (p < 2)
      return false
   if (p != 2 and p mod 2==0)
      return false;
      Compute: ll s = p - 1
   while (s mod 2 == 0)
      s = s/ 2;
      for i = 0 to iteration - 1
         Do
            ll a = rand() mod (p - 1) + 1, temp = s
            ll mod = modulo(a, temp, p)
            while (temp != p - 1 and mod != 1 and mod != p - 1)
               mod = mulmod(mod, mod, p);
               temp *= 2;
            if (mod != p - 1 && temp % 2 == 0)
               return false
            else
               return true
End

示例代码

#include <iostream>
#include<stdlib.h>
#define ll long long
using namespace std;
ll mulmod(ll a, ll b, ll m)//It returns true if number is prime otherwise false {
   ll x = 0,y = a % m;
   while (b > 0) {
      if (b % 2 == 1) {
         x = (x + y) % m;
      }
      y = (y * 2) % m;
      b /= 2;
   }
   return x % m;
}

ll modulo(ll base, ll e, ll m) {
   ll x = 1;
   ll y = base;
   while (e > 0) {
      if (e % 2 == 1)
         x = (x * y) % m;
         y = (y * y) % m;
         e = e / 2;
   }
   return x % m;
}

bool Miller(ll p, int iteration) {
   if (p < 2) {
      return false;
   }
   if (p != 2 && p % 2==0) {
      return false;
   }
   ll s = p - 1;
   while (s % 2 == 0) {
      s /= 2;
   }
   for (int i = 0; i < iteration; i++) {
      ll a = rand() % (p - 1) + 1, temp = s;
      ll mod = modulo(a, temp, p);
      while (temp != p - 1 && mod != 1 && mod != p - 1) {
         mod = mulmod(mod, mod, p);
         temp *= 2;
      }
      if (mod != p - 1 && temp % 2 == 0) {
         return false;
      }
   }
   return true;
}

int main() {
   int iteration = 10;
   ll num;
   cout<<"Enter integer to test primality: ";
   cin>>num;
   if (Miller(num, iteration))
      cout<<num<<" is prime"<<endl;
   else
      cout<<num<<" is not prime"<<endl;
   return 0;
}

输出

Enter integer to test primality: 26
26 is not prime

更新于: 30-Jul-2019

970 次浏览

开启您的 职场生涯

通过完成课程获得认证

开始学习
广告