Linear Sieve Method for Prime Numbers

Problem description:When we calculate for prime numbers with a sieve method,we delete so many numbers which is not necessary repeatly.For instance,there is a number which consists of 3x7x17x23,and we delete it when we delete the multiples of 3 as we delete the same number when we delete the multiples of 7,17,and 23.Please write a program that will not do these jobs more than once.
   
Thinking: There is a factorization theorem:every composite number could be decomposed into the multiplication of some primer numbers.Hence,the number can be decomposed in the form of (both of p andq are prime numbers and p < q).Therefore,what we need to remove is:,,...and,i=1,2,3.....The value of p and q is the numbers which are not removed currently and in a sequence from small to large.It is easy to write the program.

 

#include <stdio.h>
  #define MAX 1000
  #define null1 0
  #define NEXT(x)  x=next[x]
  #define REMOVE(x) {   previous[next[x]]=previous[x];   \
                        next[previous[x]]=next[x];       \
                    }
  
  #define INITIAL(n)  { unsigned long i;                    \
                        for(i=2;i<=n;i++)                   \
                            previous[i]=i-1,next[i]=i+1;    \
                        previous[2]=next[n]=null1;           \
                      }
  
  int main()
  {
      unsigned long previous[MAX+1]={0};
      unsigned long next[MAX+1]={0};
      unsigned long prime,fact,i,mult;
      unsigned long n;
      unsigned long count=0;
      
      scanf("%lu",&n);
  
      INITIAL(n); //initial the array
  
      for(prime=2;prime*prime<=n;NEXT(prime))
      {
          for(fact=prime;prime*fact<=n;NEXT(fact)) 
          {
              for(mult=prime*fact;mult<=n;mult*=prime) 
                  REMOVE(mult);
          }
      }
      for(i=2;i!=null1;NEXT(i))
          printf("%lu ",i),count++;
      printf("\nThe sum of the prime numbers is %lu\n",count);
  }

Reference material: C语言名题精选百则技巧篇 in Chinese.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值