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

方法一:

#include <stdio.h>

#include <windows.h>

 

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 <stdio.h>

#include <windows.h>

#include <math.h>

 

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 <stdio.h>

#include <windows.h>

#include <math.h>

 

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;

}

该方法比前面都高效。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值