{
if(wss == 1)
return 0;
int tmp = sqrt(wss);
for(int i = 2;i <= tmp;i++)
{
if(wss % i == 0)
return 0;
}
return 1;
} //这是一种非常慢的算法
PS:要使用-std=c99 -lm
int sushu(long long num)
{
if(num == 1)
return 0;
if(num == 2 || num == 3)
return 1;
if(num % 6 != 1&&num % 6 != 5)
return 0;
int tmp = sqrt(num);
for(int i = 5;i <= tmp;i += 6)
if(num %i == 0||num %(i+2) == 0)
return 0;
return 1;
}
快速算法
这两种方法的对比:
#include <stdio.h>
#include <math.h>
#include <time.h>
int sushu1(long long wss)
{
if(wss == 1)
return 0;
int tmp = sqrt(wss);
for(int i = 2;i <= tmp;i++)
{
if(wss % i == 0)
return 0;
}
return 1;
}
int sushu(long long num)
{
if(num == 1)
return 0;
if(num == 2 || num == 3)
return 1;
if(num % 6 != 1&&num % 6 != 5)
return 0;
int tmp = sqrt(num);
for(int i = 5;i <= tmp;i += 6)
if(num %i == 0||num %(i+2) == 0)
return 0;
return 1;
}
int main(void)
{
clock_t start,finish;
start = clock();
while(1)
{
srand((unsigned)time(NULL));
long long a = rand()-1;
long long b = rand()-2;
long long c = rand()-3;
long long d = a * b + c -1 ;
if(sushu(d))
{
printf("%lld is a prime.\n",d);
break;
}
else
continue;
}
finish = clock();
double cost = (double)(finish - start)/CLOCKS_PER_SEC;
printf("CPS=%ld,RT = %lf.\n",CLOCKS_PER_SEC,cost);
clock_t start1,finish1;
start1 = clock();
while(1)
{
srand((unsigned)time(NULL));
long long a = rand()-1;
long long b = rand()-2;
long long c = rand()-3;
long long d = a * b + c -1 ;
if(sushu1(d))
{
printf("%lld is a prime.\n",d);
break;
}
else
continue;
}
finish1 = clock();
double cost1 = (double)(finish1 - start1)/CLOCKS_PER_SEC;
printf("CPS=%ld,RT = %lf.\n",CLOCKS_PER_SEC,cost1);
return 0;
}
其中一个运行结果:
933190344083448553 is a prime.
CPS=1000000,RT = 12.420000. PS:方法2
1737283497230564533 is a prime.
CPS=1000000,RT = 66.880000. PS:方法1