close
標題:

C++ Program pf seiving numbers

發問:

Hey everyone, i need a program that uses the seive of Eratosthenes(don't know how to speel, sorry!) to find all the prime numbers from 1-300. Can it be as simple as possible and pls be quick! 10000x thx! =) (pls don't include iostream.h, thx!)

最佳解答:

Here's the program. As usual, if you need details, see http://mathmate.brinkster.net/ and look under programming. #include < stdio.h> #include < stdlib.h> #include < math.h> int main(int argc, char *argv[]) { int a[301],i,j; for(i=0;i<=300;i++)a[i]=1; // initialize, 1=prime, 0=composite for(i=2;i<=sqrt(300);i++) { // skip over composites if(a[i]!=0)for(j=2*i;j<=300;j+=i) a[j]=0; // mark multiples of primes except first } // print primes for(i=1;i<=300;i++)if(a[i]!=0)printf("%d ",i); } 2008-01-19 21:56:27 補充: The above code is based on making an array of numbers from 1 to 300, all initialized to 1. Starting from 2, multiples of 2 (4,6,8,...)are marked zero (composite). Then it proceeds to the next number if it is not a composite. 2008-01-19 21:56:59 補充: For 3, it marks zero for 6,9,12,15.... Four (4) has previously been marked composite, so it will not be necessary to mark multiples. This will continue until the square root of 300 (17), which is the maximum integer whose square is below 300.

此文章來自奇摩知識+如有不便請留言告知

其他解答:7638E7481407D16B
arrow
arrow
    文章標籤
    C++
    全站熱搜

    omckyyo 發表在 痞客邦 留言(0) 人氣()