gpt4 book ai didi

sql - 高效的sql素数算法

转载 作者:行者123 更新时间:2023-11-29 13:34:57 30 4
gpt4 key购买 nike

我知道 SQL 不是这方面的最佳语言,但这是一项家庭作业,需要编写一个函数,该函数将采用参数 N 并找出 1 到 1000 万之间的素数 (N=10,000,000)。我正在使用 PostgreSQL。这是我的尝试:

--First create table Numbers with all numbers from 1 to 10000000 in it

create table numbers(number bigint);

--Use this function to fill it in:

create or replace function populate(top bigint) RETURNS void as $$
declare
i bigint:=1;
begin
while(i<=top) LOOP
insert into numbers(number)
values(i);
i:=i+1;
END LOOP;
END; $$ LANGUAGE plpgsql;

--Function primes that returns all primes up to N

create or replace function primes(N bigint) RETURNS void AS $$

DECLARE
first bigint :=3;
last bigint :=2;

BEGIN
--create table t1 and insert all odd integers from 3 to N (and 2)

create table t1(a bigint);
INSERT into t1(a)
select number
from numbers
where (number%2 <> 0 or number = 2)
AND number<=N AND number<>1;

--Use Sieve of Erastothenes to find primes

while (last < sqrt(n)) LOOP

first:= (select * from t1 where a>last order by a limit 1);
last:= first* first;

--delete from list of primes all multiples of the primes in the range of first-last
-- (first run-through is primes in range of 3-9, second run-through would be primes in range of 11-121, etc.)

delete from t1
where a in (select n1.number * t.a
from t1 as t
inner join numbers as n1
on n1.number >= t.a
and n1.number<= n/t.a
where t.a>=first
and t.a<last);

END LOOP;
END; $$ LANGUAGE plpgsql;

最佳答案

对该主题的一个很好的评论在这里:https://sqlserverfast.com/blog/hugo/2006/09/the-prime-number-challenge-great-waste-of-time/

但是对于家庭作业问题,你应该自己做。

关于sql - 高效的sql素数算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15074919/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com