📅  最后修改于: 2020-09-25 06:26:43             🧑  作者: Mango
#include
using namespace std;
int main()
{
int low, high, i, flag;
cout << "Enter two numbers(intervals): ";
cin >> low >> high;
cout << "Prime numbers between " << low << " and " << high << " are: ";
while (low < high)
{
flag = 0;
for(i = 2; i <= low/2; ++i)
{
if(low % i == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
cout << low << " ";
++low;
}
return 0;
}
输出
Enter two numbers(intervals): 20 50 Prime numbers between 20 and 50 are: 23 29 31 37 41 43 47
在此程序中,while循环被迭代(high - low - 1)
次。
在每次迭代中,都会检查low
是否是素数,并将low
的值增加1,直到low
等于high
。
访问此页面以了解有关如何检查数字是否为质数的更多信息。
如果用户首先输入较大的数字,则该程序无法正常工作。如果用户首先输入较大的数字,则可以通过交换数字来解决此问题。
#include
using namespace std;
int main()
{
int low, high, flag, temp;
cout << "Enter two numbers(intevals): ";
cin >> low >> high;
//swapping numbers if low is greater than high
if (low > high) {
temp = low;
low = high;
high = temp;
}
cout << "Prime numbers between " << low << " and " << high << " are: ";
while (low < high)
{
flag = 0;
for(int i = 2; i <= low/2; ++i)
{
if(low % i == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
cout << low << " ";
++low;
}
return 0;
}
访问此页面以了解如何使用用户定义的函数显示两个时间间隔之间的所有素数。