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