You are viewing a single comment's thread. Return to all comments →
My script in python was as follows:
/* ---------------------------------------------------------------- * * IMPORTS * ---------------------------------------------------------------- */ use std::io; use std::io::BufRead; use std::collections::HashMap; /* ---------------------------------------------------------------- * * MAIN * ---------------------------------------------------------------- */ fn main() { let stdin = io::stdin(); let mut stdin_iterator = stdin.lock().lines(); let t = stdin_iterator .next() .unwrap().unwrap() .trim() .parse::<i32>() .unwrap(); let mut numbers = Vec::<i32>::new(); let mut n_max: i32 = 0; for _ in 0..t { let n: i32 = stdin_iterator .next() .unwrap().unwrap() .trim() .parse::<i32>() .unwrap(); if n > n_max { n_max = n; } numbers.push(n); } let primes = get_primes(n_max); let sums = compute_aggregates(&numbers, n_max, &primes); for n in numbers.iter() { if let Some(s) = sums.get(n) { println!("{:?}", s); } } } /* ---------------------------------------------------------------- * * HELPER METHODS * ---------------------------------------------------------------- */ fn get_primes(t: i32) -> Vec<i32> { let mut map = HashMap::<i32, bool>::new(); let mut result = Vec::<i32>::new(); for p in 2..=t { if map.get(&p) != Some(&false) { result.push(p); (2*p..=t).step_by(p as usize).for_each(|k| { map.entry(k).or_insert(false); }); } } return result; } fn compute_aggregates( numbers: &Vec<i32>, n_max: i32, primes: &Vec<i32>, ) -> HashMap::<i32, i32> { let mut primes_ = primes.clone(); primes_.push(n_max + 1); let mut sum: i32 = 0; let mut sums = HashMap::<i32, i32>::new(); let mut numbers_sorted = numbers.clone(); numbers_sorted.sort(); for n in numbers_sorted { let mut k_final: usize = 0; for (index, &p) in primes_.iter().enumerate() { k_final = index; if p > n { break; } sum += p; } primes_ = primes_[k_final..].to_vec(); sums.entry(n).or_insert(sum); } return sums; }
It passed all tests. I implemented an equivalent approach in Rust but received timeout errors for 6 and 7. Any ideas?
Seems like cookies are disabled on this browser, please enable them to open this website
Project Euler #10: Summation of primes
You are viewing a single comment's thread. Return to all comments →
My script in python was as follows:
It passed all tests. I implemented an equivalent approach in Rust but received timeout errors for 6 and 7. Any ideas?