栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

AtCode ABC149 C - Tour

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

AtCode ABC149 C - Tour

标签
  • 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 ^5 5
  • All values in input are integers.

Input

Input is given from Standard Input in the following format:

X
Output

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


Sample Input 1
20
Sample Output 1
23

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


Sample Input 2
2
Sample Output 2
2

X itself can be a prime number.


Sample Input 3
99992
Sample 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的形式代替

  • 循环判断写的妙

#include
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;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/925621.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号