Project Euler – Problem 7

By | June 2, 2011

Problem 7 from Project Euler:

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10001st prime number?

My solution:

DECLARE
    v_cnt PLS_INTEGER := 1;
    v_curr PLS_INTEGER := 2;
    c_num_prime CONSTANT PLS_INTEGER := 10001; 

    FUNCTION is_prime
    (   num_in IN NUMBER
    )
    RETURN BOOLEAN
    IS
        v_is_prime BOOLEAN := TRUE;
    BEGIN

        FOR i in 2..ceil(sqrt(abs(num_in)))
        LOOP
            IF mod(num_in,i) = 0
            THEN
                v_is_prime := FALSE;
                exit;
            END IF;
        END LOOP;

        RETURN v_is_prime;

    END is_prime;
BEGIN
    WHILE v_cnt < c_num_prime
    LOOP
        v_curr := v_curr + 1;
        IF is_prime(v_curr)
        THEN
            v_cnt := v_cnt + 1;
        END IF;            
    END LOOP;
    dbms_output.put_line('prime #'||c_num_prime||': '||v_curr);
END;

As always.. I am no mathmatician, so If you know of a better solution please let me know.

Leave a Reply

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

Turn on pictures to see the captcha *