Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created February 2, 2026 23:19
Show Gist options
  • Select an option

  • Save rust-play/07a1406a322631e7d7d8b9a4bdb03a66 to your computer and use it in GitHub Desktop.

Select an option

Save rust-play/07a1406a322631e7d7d8b9a4bdb03a66 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
// To run this, you can use: cargo run
// Or if using a single file: rustc constants.rs && ./constants
use std::fmt::Write;
/// Generates the Champernowne constant string: 0.123456789101112...
fn generate_champernowne(n_digits: usize) -> String {
let mut result = String::from("0.");
let mut current = 1;
while result.len() - 2 < n_digits {
write!(result, "{}", current).unwrap();
current += 1;
}
result.truncate(n_digits + 2);
result
}
/// Generates primes using a Sieve of Eratosthenes up to a limit
fn sieve_primes(limit: usize) -> Vec<usize> {
let mut is_prime = vec![true; limit + 1];
is_prime[0] = false;
is_prime[1] = false;
for p in 2..=((limit as f64).sqrt() as usize) {
if is_prime[p] {
for i in (p * p..=limit).step_by(p) {
is_prime[i] = false;
}
}
}
is_prime
.into_iter()
.enumerate()
.filter_map(|(i, prime)| if prime { Some(i) } else { None })
.collect()
}
/// Generates the Copeland-Erdős constant string: 0.23571113171923...
fn generate_copeland_erdos(n_digits: usize) -> String {
let mut result = String::from("0.");
// We estimate the upper bound for primes needed.
// For a large number of digits, we may need a larger sieve.
let mut sieve_limit = 1000;
let mut primes = sieve_primes(sieve_limit);
let mut prime_idx = 0;
while result.len() - 2 < n_digits {
if prime_idx >= primes.len() {
// If we run out of primes, expand the sieve
sieve_limit *= 2;
primes = sieve_primes(sieve_limit);
}
write!(result, "{}", primes[prime_idx]).unwrap();
prime_idx += 1;
}
result.truncate(n_digits + 2);
result
}
fn main() {
let digit_target = 100;
println!("--- Mathematical Constants in Rust ---");
let champernowne = generate_champernowne(digit_target);
println!("\nChampernowne Constant (C10):");
println!("{}", champernowne);
let copeland_erdos = generate_copeland_erdos(digit_target);
println!("\nCopeland-Erdős Constant:");
println!("{}", copeland_erdos);
println!("\nVerification:");
println!("Every finite digit pattern is expected to appear in these sequences");
println!("due to their proved normality in base 10.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment