back to blog index

The bigger the primorial you use

The bigger the primorial you use, the fewer are the divisors that you will
end up producing and checking. You can generalize this approach by
creating a table with primorials and another table with the coprimes of
each primorial (should take about a minute for the following code to
run):

-- create and populate table primorials

if object_id('dbo.primorials') is not null

  drop table dbo.primorials;

go

create table dbo.primorials

(

  p         bigint not null constraint pk_primorials primary key,

  primorial bigint not null constraint unq_primorial unique

);

 

insert into dbo.primorials(p, primorial) values(2, 2);

insert into dbo.primorials(p, primorial) values(3, 6);

insert into dbo.primorials(p, primorial) values(5, 30);

insert into dbo.primorials(p, primorial) values(7, 210);

insert into dbo.primorials(p, primorial) values(11, 2310);

insert into dbo.primorials(p, primorial) values(13, 30030);

insert into dbo.primorials(p, primorial) values(17, 510510);

insert into dbo.primorials(p, primorial) values(19, 9699690);

go

 

-- create and populate table coprimes

-- should take about a minute

if object_id('dbo.coprimes') is not null

  drop table dbo.coprimes;

go

create table dbo.coprimes

(

  primorial bigint not null,

  coprime   bigint not null,

  constraint pk_coprimes primary key(primorial, coprime)

);

 

declare @primorial as bigint;

 

declare cursor_primorials cursor fast_forward for

  select primorial from dbo.primorials order by primorial;

 

open cursor_primorials;

 

fetch next from cursor_primorials into @primorial;

 

while @@fetch_status = 0

begin

  insert into dbo.coprimes(primorial, coprime)

    select @primorial, n from dbo.fn_nums(1, @primorial)

    where not exists(select * from dbo.primorials

                     where primorial <= @primorial and n % p = 0);

 

  fetch next from cursor_primorials into @primorial;

end

 

close cursor_primorials;

 

deallocate cursor_primorials;

go

 

Prev. page     1 2 [3] 4 5 6 7     next page


You must log on before posting a comment.

If you don't have a username & password, please register now.

 

  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30     
or

More blogs about technology,
databases, and SQL Server.