题目描述
Alice 在纸条上写了一个质数,第二天再看时发现有些地方污损看不清了。
- 在大于 1 的自然数中,除了 1 和它本身以外不再有其他因数的自然数称为质数
请你帮助 Alice 补全这个质数,若有多解输出数值最小的,若无解输出 −1。
例如纸条上的数字为 1∗(∗ 代表看不清的地方),那么这个质数有可能为 11,13,17,19,其中最小的为 11。
输入格式
第一行 1 个整数 t,代表有 t 组数据。
接下来 t 行,每行 1 个字符串 s 代表 Alice 的数字,仅包含数字或者 ∗,并且保证首位不是 ∗ 或者 0。
输出格式
输出 t 行,每行 1 个整数代表最小可能的质数,或者 −1 代表无解。
#include <bits/stdc++.h>
using namespace std;
int t;
string s;
int len;
int res;
bool check(int x) {//素数判断
if (x < 3) return x > 1;
if (x % 2 == 0 || x % 3 == 0) return false;
for (int i = 5; i * i < x; i += 6) {
if (x % i == 0 || x % (i + 2) == 0) {
return false;
}
}
return true;
}
void dfs(int pos) {
if (pos == len) {
int num = stoi(s);//字符转数字
if (check(num)) {
if (res == -1 || res > num) {
res = num;
}
}
return;
}
if (s[pos] == '*') {
for (char i = (pos == '0' ? '1' : '0'); i <= '9'; i++) {
s[pos] = i;
dfs(pos + 1);
}
s[pos] = '*';//回溯
} else {
dfs(pos + 1);
}
}
int main() {
cin >> t;
while (t--) {
cin >> s;
len = s.size();
res = -1;
dfs(0);
cout << res << endl;
}
return 0;
}