Project Euler #10: Summation of primes

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