C语言回顾经典题之判断素数的方法

方法一:

#include 

#include 

 

int main()

{

int i = 100;

int count = 0;

for (; i <= 200; i++)  //遍历需要求的数100-200

{

int j = 2;

for (; j < i; j++) 

{

if (i%j == 0)

{

break;

}

}

if (i == j)

{

printf("%d ", i);

count++;

}

}

printf("\ncount = %d\n", count);

 

system("pause");

return 0;

}

该方法缺点:若i不是素数,则需要遍历i-1次,浪费时间。

方法二:

int main()

{

int i = 100;

int count = 0;

for (; i <= 200; i++)

{

int j = 2;

for (; j <= i/2; j++)  //当i不是素数则必定有一个数小于i/2。如10=2*5。2小于10/2。

{

if (i%j == 0)

{

break;

}

}

if (j > i / 2)

{

printf("%d ", i);

count++;

}

}

printf("\ncount = %d\n", count);

 

system("pause");

return 0;

}

方法二的优点就在于不是素数的情况。

方法三:

#include 

#include 

#include 

 

int main()

{

int i = 100;

int count = 0;

for (; i <= 200; i++)

{

int j = 2;

for (; j <= sqrt(i); j++)

{

if (i%j == 0)

{

break;

}

}

if (j > sqrt(i))

{

printf("%d ", i);

count++;

}

}

printf("\ncount = %d\n", count);

 

system("pause");

return 0;

}

法三和二的优点基本相同,比二更高效一些。

方法四:

#include 

#include 

#include 

 

int main()

{

int i = 101;

int count = 0;

for (; i <= 200; i+=2) //因为偶数都不是素数,所以只判断奇数的情况

{

int j = 2;

for (; j <= sqrt(i); j++)

{

if (i%j == 0)

{

break;

}

}

if (j > sqrt(i))

{

printf("%d ", i);

count++;

}

}

printf("\ncount = %d\n", count);

 

system("pause");

return 0;

}

该方法比前面都高效。


C语言回顾经典题之判断素数的方法_第1张图片

你可能感兴趣的:(C语言回顾经典题之判断素数的方法)