Technical Article

Another Prime Number Generator

,

This version uses the Sieve of Eratosthenes algorithm, which is very fast for moderate upper bounds, but which may be slower than the other versions when the upper bound is very large (because of the overhead of the initial table population)

set nocount on

declare 
@prime Table(
primen bigint not null primary key
)
declare 
@index bigint, 
@upper_bound bigint

select 
@upper_bound = 100000,
@index = 3

insert into @prime values (2)

while 
@index <= @upper_bound 
begin
insert
@prime
values
(@index)

select @index = @index + 2
end


select @index = 3

while 
@index <= (sqrt(@upper_bound)) 
begin
delete 
@prime 
where 
primen % @index = 0 and 
primen > @index

select @index = @index + 2
end

select * from @prime

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating