C和指针之用拉托斯特尼筛方法(Eratosthenes)查找区间质素个数

来源:互联网 发布:购物群软件 编辑:程序博客网 时间:2024/05/29 16:59

1、问题

用拉托斯特尼筛方法(Eratosthenes)查找区间质素个数



2、代码实现

#include <stdio.h>#define LEN 10000/** *Eratosthenes-埃拉托斯特尼筛方法找质数,给出要筛数值的范围n,先用2去筛,2的倍数不是质数, * 再用下一个素数,也就是3筛,把3留下,把3的倍数不是质数,接下去用下一个素数5筛,把5留下,把5的倍数不是质数, *c不断重下去...... * 求区间质素个数 */int get_all(char *a, int start, int end){   if (end > LEN)      return 0;   int count = 0;   //初始化,把每个元素设置'1'   for (int i = start; i < end; i++)       *(a + i) = '1';   //把下标不是质素的数组元素设置为‘0’   for (int i = 2;  i * i <= end; ++i)       if (*(a + i) == '1')          for (int j = 2; j * i < end; ++j)               *(a + i * j) = '0';   //打印质数   for (int i = start; i < end; ++i)       if (*(a + i) == '1')           count++;   return count;}int main(){   char a[LEN];   int result = get_all(a, 2, 50);   printf("result is %d\n", result);   int result1 = get_all(a, 10, 30);   printf("result1 is %d\n", result1);   int result3 = get_all(a, 10, 50);   printf("result3 is %d\n", result3);   return 0;}        





3、运行结果

1111deMacBook-Pro:Music a1111$ gcc -g z2.c -o z21111deMacBook-Pro:Music a1111$ ./z2result is 15result1 is 6result3 is 11




阅读全文
0 0