Last active
June 3, 2023 09:26
-
-
Save woodRock/439a4192ad006280abad9fabe643d8b3 to your computer and use it in GitHub Desktop.
Postgres function to give first n prime numbers in SQL.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
create or replace function primes(n int) | |
returns setof int as $$ | |
declare | |
i integer := 2; | |
p integer := 0; | |
j integer := 0; | |
begin | |
while i <= n loop | |
j := floor(sqrt(i)); | |
p := 1; | |
while j > 1 loop | |
if i % j = 0 then | |
p := 0 | |
exit; | |
end if; | |
j := j-1; | |
end loop; | |
if p = 1 then | |
return next i; | |
end if; | |
i = i+1; | |
end loop; | |
end; | |
$$ LANGUAGE plpgsql; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment