Project Euler #10: Summation of primes

Sort by

recency

|

211 Discussions

|

  • + 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)

  • + 0 comments

    C#

    using System;

    class MainClass { public static void Main (string[] args) { const int SIZE = 1000000; bool[] isPrime = new bool[SIZE + 1]; Array.Fill(isPrime, true); long[] sums = new long[SIZE + 2]; for (int i = 2; i <= SIZE; i++) { if (isPrime[i]) { sums[i] = sums[i-1] + i; for (long j = (long) i * i; j <= SIZE; j+=i) { isPrime[(int)j] = false; } } else { sums[i] = sums[i-1]; } }

        int t = int.Parse(Console.ReadLine());
        for (int a0 = 0; a0 < t; a0++) {
            int n = int.Parse(Console.ReadLine());
            Console.WriteLine(sums[n]);
        }
    }
    

    }

  • + 0 comments

    In C#:

    using System; using System.Collections.Generic;

    public class Solution { public static void Main(string[] args) { List primes = new List(); for (long i = 2; i <= 1000000; i++) { if (IsPrime(i)) primes.Add(i); }

        int t = Convert.ToInt32(Console.ReadLine());
        for (int a0 = 0; a0 < t; a0++) {
            int n = Convert.ToInt32(Console.ReadLine());
            long sum = 0;
            foreach (long num in primes) {
                if (num > n) break;
                sum += num;
            }
            Console.WriteLine(sum);
        }
    }
    
    public static 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;
    }
    

    }

  • + 0 comments

    Used sieve of eratosthenes and also created another array to keep track of the sums (got the idea from a comment here)

    public static void main(String[] args) {
            final int SIZE = 1000000;
            boolean[] isPrime = new boolean[SIZE + 1];
            Arrays.fill(isPrime, true);
            long[] sums = new long[SIZE + 2];
            for (int i = 2; i <= SIZE; i++) {
                if (isPrime[i]) {
                    sums[i] = sums[i-1] + i;
                    for (long j = (long) i * i; j <= SIZE; j+=i) {
                        isPrime[(int)j] = false;
                    }
                } else {
                    sums[i] = sums[i-1];
                }
            }
            
            Scanner in = new Scanner(System.in);
            int t = in.nextInt();
            for(int a0 = 0; a0 < t; a0++){
                int n = in.nextInt();
                System.out.println(sums[n]);
            }
        }