diff --git a/append_digit_primes/src/main.rs b/append_digit_primes/src/main.rs index 3e0a9f4..604bd5c 100644 --- a/append_digit_primes/src/main.rs +++ b/append_digit_primes/src/main.rs @@ -70,10 +70,11 @@ fn step(x: u64) -> Vec { } fn main() { - let mut tree = Tree::new(0, vec![2, 3, 5, 7]); + let primes: Vec = primal::Primes::all().skip_while(|x| *x < 10_000_000).take_while(|x| *x < 100_000_000).map(|x| x as u64).collect(); + let mut tree = Tree::new(0, primes); for _ in 0..20 { tree.step(); println!("{:?}", tree.longest_path()); } - println!("{}", tree.to_string()); + //println!("{}", tree.to_string()); } diff --git a/cpp/a.out b/cpp/a.out new file mode 100755 index 0000000..b86fe2a Binary files /dev/null and b/cpp/a.out differ diff --git a/cpp/append_digit_primes.cpp b/cpp/append_digit_primes.cpp new file mode 100644 index 0000000..39c50f7 --- /dev/null +++ b/cpp/append_digit_primes.cpp @@ -0,0 +1,103 @@ +#include +#include +#include +#include + +using ull = unsigned long long; + +auto next(ull x) -> std::vector; +auto is_prime(ull n) -> bool; + +class Tree +{ +public: + ull value; + std::vector children; + + Tree(ull value, std::vector tree_children) : value(value) { + for (ull child : tree_children) { + children.push_back(Tree(child, {})); + } + } + + void step() { + if (children.size() == 0) { + auto xs = next(value); + for (auto val : xs) { + children.push_back(Tree(val, {})); + } + return; + } + for (auto &child : children) { + child.step(); + } + } + + auto longest_path() -> std::vector { + if (children.size() == 0) { + return { value }; + } + std::vector max_path; + int max_length = 0; + for (auto &child : children) { + auto temp = child.longest_path(); + if (temp.size() > max_length) { + max_length = temp.size(); + max_path = temp; + } + } + std::vector retval = { value }; + retval.insert(retval.end(), max_path.begin(), max_path.end()); + return retval; + } +}; + +auto next(ull x) -> std::vector { + std::vector new_xs = {}; + ull temp = x * 10; + for (int i = 0; i < 10; i++) { + auto temp2 = temp + i; + if (is_prime(temp2)) { + new_xs.push_back(temp2); + } + } + return new_xs; +} + +auto is_prime(ull n) -> bool { + static std::unordered_map primes; + if (primes.count(n) > 0) { + return primes[n]; + } + for (int i = 2; i * i <= n; i++) { + if (n % i == 0) { + primes[n] = false; + return false; + } + } + primes[n] = true; + return true; +} + +template +auto print_vec(std::vector vec) -> void { + std::cout << '['; + for (T &val : vec) { + std::cout << val << ", "; + } + std::cout << "]\n"; +} + +auto main() -> int { + std::vector primes; + for (int i = 2; i < 10000000; i++) { + if (is_prime(i)) { + primes.push_back(i); + } + } + Tree tree(0, primes); + for (int i = 0; i < 200; i++) { + tree.step(); + print_vec(tree.longest_path()); + } +}