编写一个程序,求1~n中的素数的个数,给出两种解法。对于相同的n,给出这两种解法的结果和求解时间。
方法1:为判断整数x是否为素数,依次用2~(x-1)去除x,根据x是否能被整除作出判断;
方法2:为判断整数x是否为素数,依次用2~sqrt(x)去除x,根据x是否能被整除作出判断;
#include <iostream>
#include <time.h>
#include <math.h>
using namespace std;
bool is_prime1(int x);
bool is_prime2(int x);
void IsprimeMethod1(int n);
void IsprimeMethod2(int n);
int main()
{
int n ;
cout << "n <= 1000000:";
cin >> n;
if (n <= 100000)
{
return 0;
}
IsprimeMethod1(n);
cout << endl;
IsprimeMethod2(n);
return 0;
}
bool is_prime1(int x)
{
if(x <= 1)
{
return false;
}
for(int i = 2; i < x; i ++ )
if(x % i == 0)
{
return false;
}
return true;
}
bool is_prime2(int x)
{
if(x <= 1)
{
return false;
}
for(int i = 2; i <= sqrt(x); i ++ )
if(x % i == 0)
{
return false;
}
return true;
}
void IsprimeMethod1(int n)
{
clock_t t; //定义时钟变量
int count = 0;
t = clock();
for (int i = 1; i <= n; i ++ )
if(is_prime1(i)) count ++;
t = clock() - t;
cout << "方法1:\n";
cout << "结果1~" << n << "素数的个数为: " << count << endl;
cout << "用时为: " << ((float)t / CLOCKS_PER_SEC )<< "秒" << endl;
}
void IsprimeMethod2(int n)
{
clock_t t; //定义时钟变量
int count = 0;
t = clock();
for (int i = 1; i <= n; i++ )
if(is_prime2(i))
{
count ++;
}
t = clock() - t;
cout << "方法2:\n";
cout << "结果1~" << n << "素数的个数为: " << count << endl;
cout << "用时为: " << ((float)t / CLOCKS_PER_SEC )<< "秒" << endl;
}
求1~n中的素数
于 2022-04-12 16:37:57 首次发布