实现平方探测法。注意代码中平方探测法探测过程中的易错点
#include <iostream>
#include <cmath>
using namespace std;
const int maxn = 10001;
int hashTable[maxn] = {};
int ans[maxn];
bool isPrime(int x){
if(x <= 1)
return false;
int sqr = (int)sqrt(1.0 * x);
for(int i = 2; i <= sqr; i++){
if(x % i == 0)
return false;
}
return true;
}
int main(){
int m, n;
cin >> m >> n;
while(!isPrime(m)){
m++;
}
for(int i = 0; i < n; i++){
int key;
cin >> key;
int index = key % m;
if(hashTable[index] == 0){
ans[i] = index;
hashTable[index] = 1;
}
else{
int k = 1, test = index;
while(k < m){
test = (index + k * k) % m; //易错,错误写法:index = (index + k * k) % m;
k++;
if(hashTable[test] == 0){
ans[i] = test;
hashTable[test] = 1;
break;
}
}
if(k == m){
ans[i] = -1;
}
}
}
for(int i = 0; i < n; i++){
if(ans[i] >= 0){
cout << ans[i];
}else{
cout << "-";
}
if(i < n - 1){
cout << " ";
}else{
cout << endl;
}
}
return 0;
}