Project Euler in PL/SQL: Problem 10

  • by

This problem rounds out the first 10 Project Euler problems! Here we’ll utilize the EULER_PKG again to make for an easy solution.

Problem 10:

Summation of Primes

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

This solution was easy enough, we simply loop through the numbers below 2,000,000 and check if each is prime using our EULER_PKG.is_prime function. You could alternatively start the value of i at 5 (since we know 2 and 3 are primes) and increment i by 2 each time which should cut down on the processing time, but I found that it took the same exact time to process either way.

DECLARE
answer NUMERIC := 0;
upper_limit PLS_INTEGER := 2000000;
i PLS_INTEGER := 1;
BEGIN
    FOR i IN 1..upper_limit LOOP
        IF EULER_PKG.is_prime(i)
        THEN
            answer := answer + i;
        END IF;
    END LOOP;
    
    dbms_output.put_line(answer);
END;
--output: 142913828922

Questions or comments? Feel free to leave them below or reach out to me on Twitter!

Leave a Reply

Your email address will not be published. Required fields are marked *