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.
Project Euler #10: Summation of primes
Project Euler #10: Summation of primes
Sort by
recency
|
211 Discussions
|
Please Login in order to post a comment
Java8:)
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
}
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
}
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)
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]; } }
}
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); }
}
Used sieve of eratosthenes and also created another array to keep track of the sums (got the idea from a comment here)