[英]C++: find first prime number larger than a given integer
Question: How to find, for a given integer n
, the first prime number that is larger than n
? 问:如何找到,对于给定的整数n
,第一个素数大于n
?
My own work so far 到目前为止我自己的工作
I've managed to write a program that checks whether or not a given integer is a prime or not: 我设法编写了一个程序来检查给定的整数是否是质数:
#include <iostream>
#include <cmath>
using namespace std;
bool is_prime (int n)
{
int i;
double square_root_n = sqrt(n) ;
for (i = 2; i <= square_root_n ; i++)
{
if (n % i == 0){
return false;
break;
}
}
return true;
}
int main(int argc, char** argv)
{
int i;
while (true)
{
cout << "Input the number and press ENTER: \n";
cout << "To exit input 0 and press ENTER: \n";
cin >> i;
if (i == 0)
{
break;
}
if (is_prime(i))
cout << i << " is prime" << endl;
else
cout << i << " isn't prime'" << endl;
}
return 0;
}
I'm struggling, however, on how to proceed on from this point. 但是,我正在努力从这一点着手。
You have a function is_prime(n)
, and a number n
, and you want to return the smallest number q
such that is_prime(q)==true
and n <= q
: 您有一个函数is_prime(n)
和一个数字n
,并且您想要返回最小的数字q
这样is_prime(q)==true
和n <= q
:
int q = n;
while (!is_prime(q)) {
q++;
}
// here you can be sure that
// 1. q is prime
// 2. q >= n -- unless there was an overflow
If you want to be a bit more efficient, you can check explicitly for the even case, and the increment by 2 each time. 如果您想提高效率,可以显式检查偶数情况,并每次增加2。
It's a concrete example of a general theme: if you have a test function and a method for generating elements, you can generate the elements that pass the test: 这是一个通用主题的具体示例:如果您具有测试功能和用于生成元素的方法,则可以生成通过测试的元素:
x = initial_value
while (something) {
if (test(x)) {
// found!
// If you only want the first such x, you can break
break;
}
x = generate(x)
}
(note that this is not a valid C++ code, it's pseudocode) (请注意,这不是有效的C ++代码,它是伪代码)
int i;
**int k_koren_od_n = (int)(sqrt(n) + 0.5)**
for (i = 2; i <= k_koren_od_n ; i++){
To get around casting issues, you might want to add this fix. 要解决投放问题,您可能需要添加此修复程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.