题目:
设计一个函数,判别一个整数是否为素数。
代码:
#include <iostream>
using namespace std;
int function(int x);
int main()
{
int x;
cout << "判别一个整数是否为素数" << endl << endl;
cout << "请输入一个整数:";
cin >> x;
if (function(x) == 0) cout << endl << x << "不是素数" << endl << endl;
if (function(x) == 1) cout << endl << x << "是素数" << endl << endl;
system("pause");
return 0;
}
int function(int x)
{
//素数的定义为大于1的自然数
if (x <= 1) return 0;
//排除掉无法用开平方法的整数
else if ((x == 2) | (x == 3) | (x == 5) | (x == 7)) return 1;
//偶数显然不是素数
else if (x % 2 == 0) return 0;
//试除
else
{
for (int i = 3; i <= sqrt(x); ++i)
{
if (x % i == 0) return 0;
}
//什么事也没发生,成功逃离
return 1;
}
}