Additive primes: Difference between revisions

m
→‎{{header|Rust}}: using rust v 1.58.0 features in print!() and println!()
m (→‎{{header|Rust}}: using rust v 1.58.0 features in print!() and println!())
Line 2,650:
 
===Flat implementation===
<lang Rustfsharp>
fn main() {
let limit = 500;
// all primes, starting from 3 (including non-additive), will be collected in pms
// it works ~1.5 times faster than the variant with fn is_prime(){...while...+=6...}
let mut pms = Vec::with_capacity(limit / 2 - limit / 3 / 2 - limit / 5 / 3 / 2 + 1);
let column_width = limit.to_string().len() + 1;
Line 2,662:
if pms.iter().take_while(|&&p| p * p <= u).all(|&p| u % p != 0) {
pms.push(u);
// about the same speed as while...{...+=...%.../=...}, but without mut
let sum_digits = std::iter::successors(Some(u), |&n| (n > 9).then(|| n / 10))
.fold(0, |s, n| s + n % 10);
if sum_digits == 2 || matches!(pms.binary_search(&sum_digits), Ok(_)) {
if count % 10 == 0 {
printprintln!("\n");
}
print!("{u:1column_width$}", u, column_width);
count += 1;
}
}
}
println!("\n---\nFound {count} additive primes less than {limit}", count, limit);
}
</lang>
Line 2,693:
primal implements the sieve of Eratosthenes with optimizations (10+ times faster for large limits)
 
<lang Rustfsharp>// [dependencies]
// primal = "0.3.0"
 
Line 2,708:
.filter(|&p| p < limit && sieve_primes.is_prime(sum_digits(p)))
.zip(["\n"].iter().chain(&[""; 9]).cycle())
.inspect(|(u, sn)| print!("{sn}{u:wcolumn_width$}", sn, u, w = column_width))
.count();
println!("\n---\nFound {count} additive primes less than {limit}", count, limit);
}</lang>
{{out}}
106

edits