原文: https://www.programiz.com/cpp-programming/examples/prime-interval-function
要理解此示例,您应该了解以下 C++ 编程主题:
#include <iostream>
using namespace std;
int checkPrimeNumber(int);
int main()
{
int n1, n2;
bool flag;
cout << "Enter two positive integers: ";
cin >> n1 >> n2;
cout << "Prime numbers between " << n1 << " and " << n2 << " are: ";
for(int i = n1+1; i < n2; ++i)
{
// If i is a prime number, flag will be equal to 1
flag = checkPrimeNumber(i);
if(flag)
cout << i << " ";
}
return 0;
}
// user-defined function to check prime number
int checkPrimeNumber(int n)
{
bool flag = true;
for(int j = 2; j <= n/2; ++j)
{
if (n%j == 0)
{
flag = false;
break;
}
}
return flag;
} 输出
Enter two positive integers: 12
55
Prime numbers between 12 and 55 are: 13 17 19 23 29 31 37 41 43 47 53 要打印两个整数之间的所有质数,将创建checkPrimeNumber()函数。 此函数检查数字是否为质数。
n1和n2之间的所有整数都传递给此函数。
如果传递给checkPrimeNumber()的数字是质数,则此函数返回true,否则返回false。
如果用户首先输入较大的数字,则该程序将无法正常工作。 要解决此问题,您需要先交换数字。