Skip to content

Instantly share code, notes, and snippets.

@9ary
Last active October 9, 2019 09:29
Show Gist options
  • Save 9ary/9b53d6d8934d21f71db6221584c4383f to your computer and use it in GitHub Desktop.
Save 9ary/9b53d6d8934d21f71db6221584c4383f to your computer and use it in GitHub Desktop.
Small program that finds all primes for which all truncations from the right are prime
/// Naive primality check, assumes the input is odd
fn is_prime(n: i32) -> bool {
let max = (n as f64).sqrt() as i32 + 1;
for i in (3..max).step_by(2) {
if n % i == 0 {
return false
}
}
true
}
fn main() {
let mut generations = vec![vec![2, 3, 5, 7]];
loop {
let mut next_gen = vec![];
for p in generations.last().unwrap().iter() {
for d in [1, 3, 7, 9].iter() {
let n = p * 10 + d;
if is_prime(n) {
next_gen.push(n);
}
}
}
if next_gen.is_empty() {
break
}
generations.push(next_gen);
}
for (i, gen) in generations.iter().enumerate() {
if i == 0 {
println!("Single digit ({} results):", gen.len());
} else {
println!("{} digits ({} results):", i + 1, gen.len());
}
for n in gen.iter() {
println!(" {}", n)
}
}
}
Single digit (4 results):
2
3
5
7
2 digits (9 results):
23
29
31
37
53
59
71
73
79
3 digits (14 results):
233
239
293
311
313
317
373
379
593
599
719
733
739
797
4 digits (16 results):
2333
2339
2393
2399
2939
3119
3137
3733
3739
3793
3797
5939
7193
7331
7333
7393
5 digits (15 results):
23333
23339
23399
23993
29399
31193
31379
37337
37339
37397
59393
59399
71933
73331
73939
6 digits (12 results):
233993
239933
293999
373379
373393
593933
593993
719333
739391
739393
739397
739399
7 digits (8 results):
2339933
2399333
2939999
3733799
5939333
7393913
7393931
7393933
8 digits (5 results):
23399339
29399999
37337999
59393339
73939133
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment