A Sieve Method for Prime Numbers

A Sieve Method for Prime Numbers

Problem description:Calculate the prime numbers with a sieve method.There is amagical 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 1sieve[ main() 9 {10int i,k;11int prime;12int count=1;//The sum number of the prime numbers (i=0;i<MAX;i++)15 {{prime=i+i+3; 20count++;21for(k=prime+i;k<=MAX;k+=prime)22sieve[k]=DELETE;23 }24 },2);(i=0,k=2;i<MAX;i++)28 {29if(sieve[i]==SAVE)30 {31if(k>10) 32 {); 34k=1;35 }36int temp=i+i+3;,temp);38k++;39 }40 },count);;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.

posted on

,服务器空间,服务器空间,美国服务器没有行囊,没有目的,我孤独的走在路上,

A Sieve Method for Prime Numbers

相关文章:

你感兴趣的文章:

标签云: