Solovay-Stassen素性检验方案

来源:互联网 发布:淘宝售前客服是做什么? 编辑:程序博客网 时间:2024/06/05 02:37

基于欧拉判别法则的逆否命题实现的素性检验:

/****************************************                                      **                                      **           Solovay-Stassen            **                                      **           WuQi 10153903110           **                                      **                                      ****************************************/#include <iostream>#include <ctime>#include <cstdlib>#include <cmath>//#include <windows.h>using namespace std;/// 初始条件int n = 506941;int limit = (n-1)/2;int t = 10;long long legendre  = 0;int case_num = 1;// 随机返回一个小于n的正整数bint GiveARandomNumber();// 根据欧拉判别法则的逆否命题,返回欧拉判别法则中同余式的最小正剩余long long EulerCriterionModule(int b);// 用高斯引理计算b模n的勒让德符号并返回1或-1long long LegendreSymbol(int b);int main(){int index, b;long long tmp;srand(static_cast<unsigned>(time(nullptr)));for(index = 0; index < t; index++){//Sleep(1000);b = GiveARandomNumber();cout << "case #" << case_num++ << ":" << endl << endl;cout << "/**********************************" << endl << endl;cout << "b = " << b << endl;tmp = EulerCriterionModule(b);if(tmp==n-1)            tmp = -1;cout << "b**((n-1)/2) (mod n) = " << tmp << endl;if(tmp != 1 && tmp != -1){cout << endl;cout << "**********************************/" << endl << endl;cout << "Stop in the " << case_num-1 << " round!" << endl;cout << "Break at (i)!" << endl << endl;cout << "n is not a prime number!" << endl;return 0;}//if(tmp == n-1)          //  tmp = -1;legendre = LegendreSymbol(b);cout << "The Legendre symbol is " << legendre << endl;if(tmp != legendre){cout << endl;cout << "**********************************/" << endl << endl;cout << "Stop in the " << case_num-1 << " round!" << endl;cout << "Break at (ii)!" << endl << endl;cout << "n is not a prime number!" << endl;return 0;}cout << endl;cout << "**********************************/" << endl << endl;}cout << "n = " << n << " is a prime number!" << endl;return 0;}int GiveARandomNumber()/*Pre:  Post: 随机返回一个小于n的正整数b.  Uses: time(), rand(). */{//srand(static_cast<unsigned>(time(nullptr)));int b = rand() % (n-1) + 1;// b的范围是1~n-1return b;}long long EulerCriterionModule(int b)/*Pre: b是一个随机的,小于n的正整数.  Post: 根据欧拉判别法则的逆否命题,返回欧拉判别法则中同余式的最小正剩余.  Uses: 欧拉判别法则. */{int i;long long tmp = 1;for(i = 0; i < limit; i++)        tmp = (tmp*b) % n;return tmp;}long long LegendreSymbol(int b)/*Pre: b是一个随机的,小于n的正整数.  Post: 用高斯引理计算b模n的勒让德符号并返回1或-1.  Uses: 高斯引理, pow(). */{int i, s = 0;long long tmp, half_n = n/2;// 计算b~(p-1)/2*b中最小正剩余大于p/2的个数sfor(i = 1; i <= limit; i++){tmp = i;tmp = tmp*b%n;if(tmp > half_n)s++;}cout << s << endl;tmp = pow(-1, s);return tmp;}


原创粉丝点击