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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小码匠和老码农

喜欢作者

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值