首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >AtCode ABC149 C - Tour

AtCode ABC149 C - Tour

作者头像
小码匠
发布2022-06-16 17:59:52
发布2022-06-16 17:59:52
5290
举报

标签

  • 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.

Notes

A 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
  • All values in input are integers.

Input

Input is given from Standard Input in the following format:

代码语言:javascript
复制
X

Output

Print the minimum prime number greater than or equal to X.

Sample Input 1

代码语言:javascript
复制
20

Sample Output 1

代码语言:javascript
复制
23

The minimum prime number greater than or equal to 2020 is 23.

Sample Input 2

代码语言:javascript
复制
2

Sample Output 2

代码语言:javascript
复制
2

X itself can be a prime number.

Sample Input 3

代码语言:javascript
复制
99992

Sample Output 3

代码语言:javascript
复制
100003

题意

  • 给一个整数N,求大于他的第一个质数

思路

  • 编写一个判断质数的函数
  • 循环遍历大于N的数,是质数则退出循环

题解

小码匠

Code Review

  • 函数名建议:is_prime
代码语言:javascript
复制
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的形式代替
  • 循环判断写的妙
代码语言:javascript
复制
#include<iostream>
using 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;
}

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-05-13,如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • 标签
  • 题目地址
  • 问题描述
    • Notes
    • Constraints
    • Input
    • Output
    • Sample Input 1
    • Sample Output 1
    • Sample Input 2
    • Sample Output 2
    • Sample Input 3
    • Sample Output 3
  • 题意
  • 思路
  • 题解
    • 小码匠
    • 官方题解
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档