c++版本的实现(字符串的长度n不能太大,不要超过31)
#include<iostream>
#include<string>
#include<stdlib.h>
#include<stdio.h>
#include<time.h>
#include<cmath>
#include<vector>
using namespace std;
int n; //每个string都是n位
vector<int> prime; //用于存放素数的数组
vector<string> R1;
vector<string> R2; //存放随机产生的字符串
vector<int> s; //存放R1对应的余数
vector<int> q; //存放R2对应的余数
vector<string> getStrings() //随机产生10个字符串
{
vector<string> vi;
while(vi.size() < 10)
{
string str;
int count = n;
while(count--) str += rand()%2 + '0';
vi.push_back(str);
}
return vi;
}
bool isPrime(int x) //判断是否为素数
{
if(x == 1 || x == 0) return false;
for(int i = 2; i <= sqrt(x); i++)
if(x % i == 0) return false;
return true;
}
void getPrime() //随机生成10个不大于n*n的素数
{
int p;
prime.clear();
while(prime.size() < 10)
{
p = rand() % (n*n);
if(isPrime(p)) prime.push_back(p);
}
// cout << "Prime has ten integers as follows:" << endl;
// for(int i = 0; i < 10; i++)
// cout << prime[i] << endl;
}
int Number(string str) //将字符串转变为整型
{
int index = str.size();
int res = 0;
while(index--)
res += pow(2, str.size() - index - 1) * (str[index] - '0');
return res;
}
void computeMod() //计算余数s和q
{
s.clear();
q.clear();
for(int i = 0; i < 10; i++)
{
s.push_back(Number(R1[i]) % prime[i]);
q.push_back(Number(R2[i]) % prime[i]);
}
}
void LV10()
{
getPrime();
computeMod();
int j = 0, flag = 1, count = 0;
for(int i = 0; i < 10; i++)
{
if(s[i] != q[i]) count++;
else if(flag) j = i, flag = 0;
}
if(count == 10) cout << "reject" << endl;
else
{
if(R1[j] == R2[j]) cout << "accept" << endl;
else
{
cout << "?" << endl;
LV10(); //递归地运行LV10
}
}
}
int main()
{
srand(time(NULL));
cout<<"please input the value of n:";
while(cin >> n)
{
R1 = getStrings();
R2 = getStrings();
// cout << "R1 has ten strings as follows:" << endl;
// for(int i = 0; i < 10; i++)
// cout << R1[i] << endl;
// cout << "R2 has ten strings as follows:" << endl;
// for(int i = 0; i < 10; i++)
// cout << R2[i] << endl;
LV10();
cout<<"please input the value of n:";
}
}
python版本的实现(字符串的长度n可以任意大)
# -*-coding=utf-8 -*-
import math
import random
def isPrime(n): #判断素数
if n <= 1:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
def LV10():
prime = []
while len(prime) < 10:
num = random.randint(2, n*n)
if isPrime(num):
prime.extend([num])
s = [R1[i] % prime[i] for i in range(10)]
q = [R2[i] % prime[i] for i in range(10)]
j = 0; flag = 1; count = 0
for i in xrange(10):
if s[i] != q[i]:
count += 1
elif flag > 0:
j = i; flag = 0
if count == 10:
print "reject"
else:
if R1[j] == R2[j]:
print "accept"
else:
print "?"
LV10() #当输出“?”的时候递归执行LV10算法
if __name__ == '__main__':
n = input()
maxx = pow(2, n)
R1 = [random.randint(2, maxx) for _ in range(10)]
R2 = [random.randint(2, maxx) for _ in range(10)]
LV10()