Skip to content

Commit 519a0b1

Browse files
committed
Main bitv example: prime sieve.
1 parent 7babcde commit 519a0b1

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

src/libcollections/bitv.rs

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,55 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010

11+
//! Collections implemented with bit vectors.
12+
//!
13+
//! # Example
14+
//!
15+
//! This is a simple example of the [Sieve of Eratosthenes][sieve]
16+
//! which calculates prime numbers up to a given limit.
17+
//!
18+
//! [sieve]: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
19+
//!
20+
//! ```
21+
//! use std::collections::{BitvSet, Bitv};
22+
//! use std::iter;
23+
//!
24+
//! let max_prime = 10000;
25+
//!
26+
//! // Store the primes as a BitvSet
27+
//! let primes = {
28+
//! let mut bv = Bitv::with_capacity(max_prime, true);
29+
//!
30+
//! // Neither 0 nor 1 are prime
31+
//! bv.set(0, false);
32+
//! bv.set(1, false);
33+
//!
34+
//! for i in range(2, max_prime) {
35+
//! // if i is a prime
36+
//! if bv.get(i) {
37+
//! // mark all multiples of i as non-prime (any multiples below i * i
38+
//! // will have been marked as non-prime previously)
39+
//! for j in iter::range_step(i * i, max_prime, i) { bv.set(j, false) }
40+
//! }
41+
//! }
42+
//! BitvSet::from_bitv(bv)
43+
//! };
44+
//!
45+
//! // Simple primality tests below our max bound
46+
//! let print_primes = 20;
47+
//! print!("The primes below {} are: ", print_primes);
48+
//! for x in range(0, print_primes) {
49+
//! if primes.contains(&x) {
50+
//! print!("{} ", x);
51+
//! }
52+
//! }
53+
//! println!("");
54+
//!
55+
//! // We can manipulate the internal Bitv
56+
//! let num_primes = primes.get_ref().iter().filter(|x| *x).count();
57+
//! println!("There are {} primes below {}", num_primes, max_prime);
58+
//! ```
59+
1160
#![allow(missing_doc)]
1261

1362
use core::prelude::*;

0 commit comments

Comments
 (0)