判断一个数是否为素数
思路:若一个数n不能被
2和√n之间的数整除(即取模为0),则可判断n为素数。可从2开始测试,一直到√n为止。(for循环)
代码如下:
#include<iostream>
using namespace std;
#include<string>
#include<cmath>
void is_prime(int num)
{
int dex = sqrt(num);
bool out = 1;
if (num == 2 || num == 3)cout << num << "是素数" << endl;
else if (num == 0 || num == 1)cout << num << "不是素数" << endl;
else {
for (int i = 2; i <= dex; i++)
{
if (num % i == 0)
{
out = 0;
break;
}
}
if (out)
{
cout << num << "是素数" << endl;
}
else
{
cout << num << "不是素数" << endl;
}
}
}
int main()
{
int num;
int n;
cout << "请输入要测试的个数:" << endl;
cin >> n;
for (int i = 0; i < n; i++)
{
cout << "请输入一个整数:" << endl;
cin >> num;
is_prime(num);
system("pause");//设置暂停方便观察
system("cls");//设置清屏
}
return 0;
}
|