📄 exa_7254.htm
字号:
<HTML><HEAD><TITLE>5.4 Example Program - Sieve of Eratosthenes</TITLE></HEAD><BODY><A HREF="ug1.htm"><IMG SRC="images/banner.gif"></A><BR><A HREF="boo_0584.htm"><IMG SRC="images/prev.gif"></A><A HREF="booktoc1.htm"><IMG SRC="images/toc.gif"></A><A HREF="tindex1.htm"><IMG SRC="images/tindex.gif"></A><A HREF="lis_3222.htm"><IMG SRC="images/next.gif"></A><BR><STRONG>Click on the banner to return to the user guide home page.</STRONG><H2>5.4 Example Program - Sieve of Eratosthenes</H2><A HREF="sidebar1.htm#sidebar17"><IMG SRC="images/note.gif" BORDER=0> <STRONG>Obtaining the Source</STRONG></A><A NAME="idx64"><!></A><P>An example program that illustrates the use of vectors is the classic algorithm, called the <I>sieve of Eratosthenes</I>, used to discover prime numbers. A list of all the numbers up to some bound is represented by an integer vector. The basic idea is to strike out (set to zero) all those values that cannot be primes; thus all the remaining values will be the prime numbers. To do this, a loop examines each value in turn, and for those that are set to one (and thus have not yet been excluded from the set of candidate primes) strikes out all multiples of the number. When the outermost loop is finished, all remaining prime values have been discovered. The program is as follows:</P><PRE>void main() { // create a sieve of integers, initially set const int sievesize = 100; vector<int> sieve(sievesize, 1); // now search for 1 bit positions for (int i = 2; i * i < sievesize; i++) if (sieve[i]) for (int j = i + i; j < sievesize; j += i) sieve[j] = 0; // finally, output the values that are set for (int j = 2; j < sievesize; j++) if (sieve[j]) cout << j << " "; cout << endl;}</PRE><BR><HR><A HREF="boo_0584.htm"><IMG SRC="images/prev.gif"></A> <A HREF="booktoc1.htm"><IMG SRC="images/toc.gif"></A><A HREF="tindex1.htm"><IMG SRC="images/tindex.gif"></A><A HREF="lis_3222.htm"><IMG SRC="images/next.gif"></A><P>©Copyright 1996, Rogue Wave Software, Inc.</P></BODY></HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -