Project Euler #10: Summation of primes

Sort by

recency

|

214 Discussions

|

  • + 1 comment

    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?

  • + 0 comments

    Haskell

    import Control.Applicative
    import Control.Monad
    import System.IO
    import Data.List
    
    primes = 2 : [i | i <- [3..1000000],  
                  and [rem i p > 0 | p <- takeWhile (\p -> p^2 <= i) primes]]
                 
    main :: IO ()
    main = do
        t_temp <- getLine
        let t = read t_temp :: Int
        forM_ [1..t] $ \a0  -> do
            n_temp <- getLine
            let n = read n_temp :: Int
            let primesToInput = filter (<= n) primes
            print (sum primesToInput)
    
  • + 0 comments

    include

    include

    include

    using namespace std; bool isprime(long number){ if((number != 2 && number != 3 && number != 5) && (number % 2 == 0 || number % 3 == 0 || number % 5==0))

    return false;
    
    for(long i =2; i*i <= number; i++){
        if(number % i == 0)
        return false;
    }
    return true;
    

    }

    int main(){ vector primes; for(long i = 2; i<1000000; i++){ if (isprime(i)) primes.push_back(i); }

    int t;
    cin >> t;
    for(int a0 = 0; a0 < t; a0++){
        int n;
        cin >> n;
        long sum = 0;
    
        for(long num : primes){
            if(num >n)
            break;
            sum += num;
        }
        cout << sum << endl;
    }
    
    return 0;
    

    }

  • + 0 comments

    Java8:)

    import java.io.*;
    import java.util.*;
    
    public class Solution {
    
        // Function to apply the Sieve of Eratosthenes and mark primes
        public static boolean[] sieveOfEratosthenes(int max) {
            boolean[] isPrime = new boolean[max + 1];
            Arrays.fill(isPrime, true); // Assume all numbers are prime
            isPrime[0] = false; // 0 is not prime
            isPrime[1] = false; // 1 is not prime
    
            // Sieve of Eratosthenes algorithm
            for (int i = 2; i * i <= max; i++) {
                if (isPrime[i]) {
                    for (int j = i * i; j <= max; j += i) {
                        isPrime[j] = false; // Mark all multiples of i as not prime
                    }
                }
            }
    
            return isPrime; // Return the array indicating primality of numbers
        }
    
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            
            int t = in.nextInt(); // Number of test cases
            int[] testCases = new int[t]; // Array to hold each test case
            int maxN = 0;
    
            // Read all test cases and find the maximum value of n
            for (int i = 0; i < t; i++) {
                testCases[i] = in.nextInt();
                if (testCases[i] > maxN) {
                    maxN = testCases[i]; // Find the maximum n
                }
            }
    
            // Precompute all primes up to the maximum value of n in the test cases
            boolean[] isPrime = sieveOfEratosthenes(maxN);
            long[] primeSums = new long[maxN + 1];
            long sum = 0;
    
            // Calculate the sum of primes up to each number
            for (int i = 1; i <= maxN; i++) {
                if (isPrime[i]) {
                    sum += i; // Add prime number to the sum
                }
                primeSums[i] = sum; // Store the cumulative sum
            }
    
            // For each test case, output the sum of primes up to n
            for (int i = 0; i < t; i++) {
                System.out.println(primeSums[testCases[i]]);
            }
            
            in.close();
        }
    }
    
  • + 0 comments

    Function to generate prime numbers up to a given limit

    generate_primes <- function(limit) { primes <- rep(TRUE, limit) # Assume all numbers are primes initially primes[1] <- FALSE # 1 is not prime

    for (i in 2:floor(sqrt(limit))) {
        if (primes[i]) {
            multiples <- seq(i^2, limit, by = i)  # Generate multiples of i
            primes[multiples] <- FALSE  # Mark multiples of i as non-prime
        }
    }
    
    which(primes)  # Return indices of prime numbers
    

    }

    Function to read input from stdin and compute sum of primes for each test case

    extract_prime_and_sum <- function(num_cases, n_values) { primes <- generate_primes(max(n_values)) # Generate primes up to the maximum n value

    for (n in n_values) {
        primes_below_n <- primes[primes <= n]  # Filter primes less than or equal to n
        cat(sum(primes_below_n), "\n")  # Print the sum of primes below n with a newline
    }
    

    }

    Read input from stdin

    t <- as.integer(readLines("stdin", n = 1))

    n_values <- integer(t) # Initialize a vector to store n values

    Read n values from stdin

    for (i in 1:t) { n_values[i] <- as.integer(readLines("stdin", n = 1)) }

    Call the function with the number of cases (t) and n values (n_values)

    extract_prime_and_sum(t, n_values)