Problem description:Calculate the prime numbers with a sieve method.There is a magical sieve that can remove all the multiple of the number i.Please calculate the prime numbers at a range from 2 to N by this way.There is a requirement that you should not use multiplication and division.You can only use the addition and subtraction for the speed.
The problem and the solution come from the book named C语言名题精选百则技巧篇 in Chinese.I am ashamed that I have few idea about this kind of problems which need some math knowledge.I need do practice more in this aspect.
I made a summary about the thinking of that book and added some my own idea.
1. The multiples of 2 are not prime so we don't think about them. 2 is prime,so the set should be discussed is 2i+3,i=0,1,2,3,4........
2. We just need deal with the numbers up to the half the number to be tested. We base the MAX in the code,calculate the prime between 2 to 2*MAX+3 but we just stop i at the MAX with our program.
3. We can not use the multiplication and division but addition and subtraction,so we must do something in math aspect : 2i+3 is odd numbers and we need to remove their multiples.In the 1st point,we have already removed the multiple of 2 so that we can ignore the even multiples of 2i+3.Now our goal is to deal with the odd multiples of 2i+3.Therefore,we want to delete the (2n+1)(2i+3),n=1,2,3,4......Of course we can not remove the 2i+3 itself.Then change the (2n+1)(2i+3) into the form 2N+3(I remembered that I often do it in my math proofs).The procedure is : (2n+1)(2i+3)=2n(2i+3)+2i+3=2[n(2i+3)+i]+3;This is a form of 2N+3(N is n(2i+3)+i).Because we use i as a index so what we pick the numbers located at N by the sieve method are the numbers located at n(2i+3)+i.Finally,we can write a program with the thinking above.
1 #include <stdio.h>
2 #define MAX 1000
3 #define SAVE 0
4 #define DELETE 1
5
6 int sieve[1000]={0}; //all to SAVE
7
8 int main()
9 {
10 int i,k;
11 int prime;
12 int count=1;//The sum number of the prime numbers
13 //2*i+3 is odd numbers
14 for(i=0;i<MAX;i++)
15 {
16 if(sieve[i]==SAVE) //it is a prime number
17 {
18 //I have a problem here.Why are the front several numbers prime number after one or two sieve process such as 5 or 7 or 11? I just think they are prime nubmers without proving it.
19 prime=i+i+3;
20 count++;
21 for(k=prime+i;k<=MAX;k+=prime)
22 sieve[k]=DELETE;
23 }
24 }
25 printf("%6d",2);
26
27 for(i=0,k=2;i<MAX;i++)
28 {
29 if(sieve[i]==SAVE)
30 {
31 if(k>10)
32 {
33 printf("\n");
34 k=1;
35 }
36 int temp=i+i+3;
37 printf("%6d",temp);
38 k++;
39 }
40 }
41 printf("\nThe sum number is %d \n",count);
42 return 0;
43 }
Summary:I am poor in the problems with math knowledge.I can hardly come up with a great idea to solve it.The root cause for this is that I don't have enough math knowlege and the lack of practice.From now on,I will practice more algorithm or data structure problems with math and program,even some projects.
Reference material: C语言名题精选百则技巧篇 in Chinese.