C++ Program pf seiving numbers

2008-01-19 7:18 am
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!)

回答 (1)

2008-01-19 4:32 pm
✔ 最佳答案
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.


收錄日期: 2021-04-13 14:59:06
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20080118000051KK03932

檢視 Wayback Machine 備份