We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
importjava.io.*;importjava.util.*;publicclassSolution{// Function to apply the Sieve of Eratosthenes and mark primespublicstaticboolean[]sieveOfEratosthenes(intmax){boolean[]isPrime=newboolean[max+1];Arrays.fill(isPrime,true);// Assume all numbers are primeisPrime[0]=false;// 0 is not primeisPrime[1]=false;// 1 is not prime// Sieve of Eratosthenes algorithmfor(inti=2;i*i<=max;i++){if(isPrime[i]){for(intj=i*i;j<=max;j+=i){isPrime[j]=false;// Mark all multiples of i as not prime}}}returnisPrime;// Return the array indicating primality of numbers}publicstaticvoidmain(String[]args){Scannerin=newScanner(System.in);intt=in.nextInt();// Number of test casesint[]testCases=newint[t];// Array to hold each test caseintmaxN=0;// Read all test cases and find the maximum value of nfor(inti=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 casesboolean[]isPrime=sieveOfEratosthenes(maxN);long[]primeSums=newlong[maxN+1];longsum=0;// Calculate the sum of primes up to each numberfor(inti=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 nfor(inti=0;i<t;i++){System.out.println(primeSums[testCases[i]]);}in.close();}}
Cookie support is required to access HackerRank
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 →
Java8:)