Sunday, December 25, 2011

Postgresql - plpgsql - Generating primes

I deemed it appropriate to start with plpgsql once and for all. So this is the plpgsql version of the algorithm (Eratosthenes' sieve) I implemented with javascript. This is my first plpgsql function ever, so I guess many improvements/corrections are in order.

CREATE OR REPLACE FUNCTION primes( upLim INTEGER ) RETURNS VOID AS
$$
DECLARE
nums boolean [];
BEGIN

FOR i IN 2..upLim LOOP
nums[i] = true;
END LOOP;
FOR i IN 2..TRUNC(|/upLim) LOOP
IF nums[i] = true
THEN
FOR j IN 2..upLim LOOP
nums[i*j] = false;
EXIT WHEN i * j > upLim;
END LOOP;
END IF;
END LOOP;

FOR i IN 2..upLim LOOP
IF nums[i] = true THEN
RAISE NOTICE '% ',i;
END IF;
END LOOP;
END;
$$ LANGUAGE plpgsql;

SELECT primes(100000) ;

Total query runtime: 242672 ms.
1 row retrieved.

Kinda slow, I must admit...mmmm

No comments:

Post a Comment