- DFS、BFS
C - Next Prime
- https://atcoder.jp/contests/abc149/tasks/abc149_c?lang=en
Find the minimum prime number greater than or equal to X.
NotesA prime number is an integer greater than 1 that cannot be evenly divided by any positive integer except 1 and itself.
For example, 2, 3, and 5 are prime numbers, while 4 and 6 are not.
Constraints- 2 ≤ le ≤ X ≤ le ≤ 10 5 ^5 5
- All values in input are integers.
Input
Input is given from Standard Input in the following format:
XOutput
Print the minimum prime number greater than or equal to X.
Sample Input 1
20Sample Output 1
23
The minimum prime number greater than or equal to 2020 is 23.
Sample Input 2
2Sample Output 2
2
X itself can be a prime number.
Sample Input 3
99992Sample Output 3
100003题意
- 给一个整数N,求大于他的第一个质数
- 编写一个判断质数的函数
- 循环遍历大于N的数,是质数则退出循环
-
Code Review
-
函数名建议:is_prime
-
1的判断最好加上(虽然题目 x > 2)
if (x <= 1) return false;
-
bool prime_number(int x) {
for(int i = 2; i < sqrt(x); i++) {
if(x % i == 0) {
return false;
}
}
return true;
}
void coder_solution() {
// 提升cin、cout效率
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
for (int i = n; 1; i++) {
if(prime_number(i)) {
cout << i;
break;
}
}
}
官方题解
-
一般不要写死循环,容易出问题
-
sqrt函数记不起来时,可以用i*i的形式代替
-
循环判断写的妙
#includeusing namespace std; bool is_prime(int x){ if (x <= 1) return false; for (int i = 2; i * i <= x; i++) { if(x % i == 0) return false; } return true; } signed main(){ int x; cin>>x; int p=x; while(!is_prime(p)) { p++; } cout< < p << endl; return 0; }



