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.