Project Euler #10: Summation of primes

  • + 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();
        }
    }